Java - Get a given objects name from another class - java

I have a basic understanding of OOP concepts, but here is a question I currently have.
Say I create this object:
Test test1 = new Test();
I then call a function within this Object
test1.toString();
And when overriding that toString() method I want to get the 'test1' object name from the main class file, so I can print it out like so...
System.out.println( "This is a test " + test1.toString() );
Prints:
This is a test test1
Thank you

The name of a local variable is only meaningful at compile time. There is no way to obtain the name of a reference.
Note: the reference and the Object are two different things.
What you can do is get the name of a field, however there is no way to find from an object where the object has been assigned.
The normal way to give an Object a name, is to give a field e.g. name
Test test1 = new Test("test1");
String str = test1.getName();
For enum there is an implicit name.
enum BuySell {
Buy, Sell;
}
BuySell bs = BuySell.Buy;
String s = bs.name(); // implicitly defined for all Enum

Related

Create Object using the value of a Java variable

I need help I need to know if Java allows to create an object dynamically, using the value of a variable.
Example
// I have 2 classes:
public class Audit {
private Long idAudit
// constructors, get and set
}
publish class Example {
private Long idExample
// constructors, get and set
}
-------------------------------------------------- -----
// create Audit and Example class object
Audit objAudit = new Audit ();
Example objExample = new Example ();
my question is the following can you create an object either of type Audit or example using the value of a variable as I try to do in the following example. Example:
String className = "Audit"; // variable that contains the class of the Object to create
className auditObject = new ClassName (); // I use the variable classname to create the desired object
Clearly I get an error trying to create the object that way, my question is can I create an object dynamically or some other option to try to achieve what I need. Thank you
Reflection is what you are searching for
final String className = "Audit";
final Class<?> clazz = Class.forName(className);
final Object o = clazz.getConstructor().newInstance();
There are several ways you can do this.
One is called reflection, and I will let you read about it on your own.
The other one is called a factory pattern. You can create a class called ObjectFactory. in that class you will have a method public Object createObject(String type).
In the method you can check if the type you received is one of your known types, and based on the type you can create the instance of the correct class. It is better of your classes implement the same interface. Then of course your method would return the instance of that interface (or a common base class).

Android Java, How to get the value of class attribute?

I want to get the value a class attribute, But I am getting exception : java.lang.NoSuchFieldException
Person.class
public class Person {
public static final String name = "person name";
}
MainActivity.class
...
private void method() {
Class myClass = Person.class;
String name = myClass.getField("name");
}
...
I am getting a java.lang.NoSuchFieldException exception for the getField method.
I tried these solutions but with no avail ...
Change getField method to getDeclaredField
Surround the code by try/catch, and got another error (Incompatible types : java.lang.String and java.lang.reflect.Field)
Invalidate Android Studio caches and restart
I don't Know how to access this value, Any solutions or suggestions are welcomed.
Thanks in advance.
Change getField method to getDeclaredField
Surround the code by try/catch, and got another error (Incompatible
types : java.lang.String and java.lang.reflect.Field)
that because getDeclaredField will return object of type Field not String,
just change your code to this
Field field = myClass.getDeclaredField("name");
//do something with field
If you want to access the value of the field, you can use the get(...) method with a null argument - since it's a static field, it does not require any instance:
private void method() {
Class myClass = Person.class;
Field field = myClass.getField("name");
String name = field.get(null);
Log.d("Test", "field value: " + name);
}
In your case, it doesn't matter whether you use getField(...) or getDeclaredField(...). You would want to use the latter if you want to grab a field in its superclass or an interface implemented by your class.
For example, if Person were to extend from a class that has a field named sample, you would need to use getDeclaredField("sample") instead.
If your variable in the class "Person" is static:
(This is not the best solution in my opinion)Explanation: getField method returns a type "field" so you CAN NOT save into a variable from another type without a conversion.
YourField.get returns an object so you CAN NOT save into a variable from another type without a conversion.
try{
Class _person = Person.class;
Field field = _person.getField("name");
Object value = field.get(null);
String valueString = (String)value; /*The String you are looking for*/
}catch (Exception e) {
//TODO handle exception
}
If your variable in the class "Person" is static:
String valueString = Person.name /*The value you are looking for*/
If your variable isn't static but public:
IMPORTANT (If you have not set a default value to the variable): In this case the value will be an empty string because you are creating a new instance of your calss. You can set the "person name" in the constructor of your Person class another way you will get an empty string because the variable isn't static.
Person _person = new Person();
String personName = _person.name;
Since that's a constant you declared, access it directly with the class name as below,
String name = Person.name;
It's a static constant. Static means there is only one value at a time possible. Or say it like this: The class attribute 'name' is a class attribute, not an object attribute! The attribute belongs to the class!
So you don't need to create an instance of your Person class.
You just can use:
String name = Person.name;
Remember: this only works cause the name belongs to the class. And it does so, because you declared your name variable static.

Scala extend trait field not found

I have a scala trait with a public UUID that has a default value:
trait pet {
var uuid_ : UUID = UUID.randomUUID
}
now I am creating multiple classes, also in scala:
class dog extends pet {
var foo = 1
}
class cat extends pet {
}
class fish extends pet {
}
After that I created a method in Java (old project with both languages mixed).
Here the snipped with my problem. In the variable somePet is an instance of dog, cat or fish. But it is not clear what of them exactly:
// printing all variables in the console for human testing
Serializer.printAllFields(somePet);
// The somePet Variable must be a pet
if(!pet.class.isAssignableFrom(somePet.getClass()))
throw new Exception("Not a pet.");
// get the UUID of the pet
UUID uuid_;
try {
Field f = pet.class.getField("uuid_");
f.setAccessible(true);
uuid_ = (UUID) f.get(somePet);
}catch(Exception e){
// no uuid found
throw e;
}
But when I run the code I get the following error:
Exception in thread "main" java.lang.NoSuchFieldException: uuid_
And the stacktrace points on the line with Field f = pet.class.getField("uuid_");.
But what is wrong with the code?
An alternative I thought was replacing this exact line with:
Field f = ntObj.getClass().getField("uuid_");
But this also fails.
So where is the variable uuid_?
Because when I print out all variables in the console of the current somePet with a Serializer, I get something like
* cat.uuid_ = 34d7a781-472d-4d98-861e-7cff08045445;
or
* dog.foo = 1
* dog.uuid_ = 34d7a781-472d-4d98-861e-7cff08045445;
in the console.
So the variable uuid_ is there with a default value.
(I am using the serializer from this post)
So how do I get the uuid_ variable in my java snippet?
First of all, there is no such Serializer under the the package java.util, so you're using something else.
An trait is translated to a Java interface, which cannot have fields per se.
However you're trying to access the field via the Pet interface
pet.class.getField(...)
That won't work. You need to look for the field inside the concrete class.
Also, the field will be private by default, since the access is granted via a getter.
The getField method is able to retrieve every public field for the entire class hierarchy (which mean even superclasses), while getDeclaredField is able to retrieve protected and private fields, but only on the exact class you're calling it from. You need also a call to setAccessible(true), because
A value of true indicates that the reflected object should suppress
Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks
The correct code would be (dog is the concrete instance)
final Field uuid = dog.getClass().getDeclaredField("uuid_");
uuid.setAccessible(true);
final Object o = uuid.get(dog);
Or using the automatic getter
final Method uuid = dog.getClass().getMethod("uuid_");
final Object o = uuid_.invoke(dog);

Function from Database cannot be used anywhere in another class, java [duplicate]

Building a multi-language application in Java. Getting an error when inserting String value from R.string resource XML file:
public static final String TTT = (String) getText(R.string.TTT);
This is the error message:
Error: Cannot make a static reference to the non-static method getText(int) from the type
Context
How is this caused and how can I solve it?
Since getText() is non-static you cannot call it from a static method.
To understand why, you have to understand the difference between the two.
Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:
SomeClass myObject = new SomeClass();
To call an instance method, you call it on the instance (myObject):
myObject.getText(...)
However a static method/field can be called only on the type directly, say like this:
The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.
... = SomeClass.final
And the two cannot work together as they operate on different data spaces (instance data and class data)
Let me try and explain. Consider this class (psuedocode):
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = "0";
}
Now I have the following use case:
Test item1 = new Test();
item1.somedata = "200";
Test item2 = new Test();
Test.TTT = "1";
What are the values?
Well
in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99
In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = getText(); // error there is is no somedata at this point
}
So the question is why is TTT static or why is getText() not static?
Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?
There are some good answers already with explanations of why the mixture of the non-static Context method getText() can't be used with your static final String.
A good question to ask is: why do you want to do this? You are attempting to load a String from your strings resource, and populate its value into a public static field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context into your other classes and call context.getText(R.string.TTT) from within them.
public class NonActivity {
public static void doStuff(Context context) {
String TTT = context.getText(R.string.TTT);
...
}
}
And to call this from your Activity:
NonActivity.doStuff(this);
This will allow you to access your String resource without needing to use a public static field.
for others that find this in the search:
I often get this one when I accidentally call a function using the class name rather than the object name. This typically happens because i give them too similar names : P
ie:
MyClass myclass = new MyClass();
// then later
MyClass.someFunction();
This is obviously a static method. (good for somethings)
But what i really wanted to do (in most cases was)
myclass.someFunction();
It's such a silly mistake, but every couple of months, i waste about 30 mins messing with vars in the "MyClass" definitions to work out what im doing wrong when really, its just a typo.
Funny note: stack overflow highlights the syntax to make the mistake really obvious here.
You can either make your variable non static
public final String TTT = (String) getText(R.string.TTT);
or make the "getText" method static (if at all possible)
getText is a member of the your Activity so it must be called when "this" exists. Your static variable is initialized when your class is loaded before your Activity is created.
Since you want the variable to be initialized from a Resource string then it cannot be static. If you want it to be static you can initialize it with the String value.
You can not make reference to static variable from non-static method.
To understand this , you need to understand the difference between static and non-static.
Static variables are class variables , they belong to class with their only one instance , created at the first only.
Non-static variables are initialized every time you create an object of the class.
Now coming to your question, when you use new() operator we will create copy of every non-static filed for every object, but it is not the case for static fields. That's why it gives compile time error if you are referencing a static variable from non-static method.
This question is not new and existing answers give some good theoretical background. I just want to add a more pragmatic answer.
getText is a method of the Context abstract class and in order to call it, one needs an instance of its subclass (Activity, Service, Application or other). The problem is, that the public static final variables are initialized before any instance of Context is created.
There are several ways to solve this:
Make the variable a member variable (field) of the Activity or other subclass of Context by removing the static modifier and placing it within the class body;
Keep it static and delay the initialization to a later point (e.g. in the onCreate method);
Make it a local variable in the place of actual usage.
Yes u can make call on non-static method into static method because we need to remember first' we can create an object that's class we can call easyly on non -static method into static mathod

How to use a String value in order to call class attribute

Let's say I have Java class:
public class Animal
{
public String dog = "Rex";
}
In another class I am doing like this:
Animal mAnimal = new Animal();
String attributeCaller = "dog";
PROBLEM: how to call mAnimal attribute "dog" by using String "attributeCaller" value in Java? I mean to do something like this:
String dogName = mAnimal.attributeCaller;
which simply should be equal to (convenient way of calling attributes in Java):
String dogName = mAnimal.dog;
You can do it using Java Reflection API: http://docs.oracle.com/javase/tutorial/reflect/. However, I would not recommend using Reflection unless it is really necessary.
You can use java reflection API to inspect the content of any object and achieve that.
Here is an example:
String attributeCaller = "dog";
Animal mAnimal = new Animal();
Class<?> c = mAnimal.getClass();
Field f = c.getDeclaredField(attributeCaller);
f.setAccessible(true);
String dogName = (String) f.get(mAnimal);
Please notice that this doesn't work for superclass fields, to get superclass fields you have to iterate through c.getSuperclass() to find the field
Those seem to be two different classes so that idea will not work.
You have one class called Animal which has a String attribute called dog. Now in another class where you have created an Object of type Animal,in this case that object is called mAnimal,you have to refer to its attribute by the object name,so the variable dogName can be assigned the value of the object like:
String dogName=mAnimal.dog; or perhaps you want to set that object's attribute like:
mAnimal.dog = "Snoopy"; .It seems you may understand how Classes and Objects work, I would recommend watching the Lynda.com videos on Java for Beginners or getting the Java How To Program by the Deitel brothers.If that was helpful consider giving it a point up

Categories

Resources