How to access dynamiclly variables from another Java Class? - java

My question similar to others but it's little bit more tricky for me
I have a Class DummyData having static defined variables
public static String Survey_1="";
public static String Survey_2="";
public static String Survey_3="";
So, i call them DummyData.Survey_1 and it returns whole string value. Similarly do with DummyData.Survey_2 and DummyData.Survey_3
But the problem is when i call them Dynamically its not return their value.
I have a variable data which value is change dynamically like (data=Survey_1 or data=Survey_2 or data=Survey_3)
I use #Reflection to get its value but failed to get its value
I use methods which I'm mentioning Below help me to sort out this problem.
Field field = DummyData.class.getDeclaredField(data);
String JsonData = field.toString();
and
DummyData.class.getDeclaredField("Survey_1").toString()
but this return package name, class name and string name but not return string value.
What I'm doing can some help me??

Getting the value of a declared field is not as simple as that.
You must first locate the field. Then, you have to get the field from an instance of a class.
Field f = Dummy.class.getDeclaredField(“field”);
Object o = f.get(instanceOfDummy);
String s = (String) o;

Doing the simple toString() of the Field will actually invoke the toString() method of the Field object but won't access the value
You must do something like this:
Field field = SomeClass.class.getDeclaredField("someFieldName");
String someString = (String) field.get(null); // Since the field is static you don't need any instance
Also, beware that using reflection is an expensive and dangerous operation. You should consider redesigning your system

Related

How to get field value in Java reflection [duplicate]

This question already has answers here:
Get field values using reflection
(4 answers)
Closed 3 years ago.
I have following field in a class:
private String str = "xyz";
How do I get the value xyz using the field name only i.e.
I know the name of the field is str and then get the assigned value. Something like:
this.getClass().getDeclaredField("str").getValue();
Currently the Reflection API has field.get(object).
You can use:
String value = (String) this.getClass().getDeclaredField("str").get(this);
Or in a more generalized and safer form:
Field field = anObject.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
String value = (String) field.get(anObject);
And for your example, this should be enough:
String value = this.str;
But you probably know of that one.
Note: anObject.getClass().getDeclaredField() is potentially unsafe as anObject.getClass() will return the actual class of anObject. See this example:
Object anObject = "Some string";
Class<?> clazz = anObject.getClass();
System.out.println(clazz);
Will print:
class java.lang.String
And not:
class java.lang.Object
So for your code's safety (and to avoid nasty errors when your code grows), you should use the actual class of the object you're trying to extract the field from:
Field field = YourObject.class.getDeclaredField(fieldName);
Imagine you have object in variable foo.
Then you need to get Field
Field field = foo.getClass().getDeclaredField("str");
then allow access to private field by:
field.setAccessible(true);
and you can have value by:
Object value = field.get(foo);

How to store int and string value in bean class?

I know this is very basic question yet I am unable to get the perfect answer. I have one bean named Order in which there is one object product_size such as
public Class Order{
private String product_size;
}
Setter and Getter methods are defined respectively in that class. The problem is that product_size may contain string variable such as S or Integer value such as 7.
I am unable to store the Integer value in that bean object.
I have done with only one bean instance and I am check that if value is string it should be added in bean object Simply else Integer.toString() method will convert the int value to String.
Example is given below-
String str; // it is dynamic let there are two values in this 'S' and 8
if (str instancof String){
order.setProduct_Size(str);
}else{
order.setProduct_Size(Integer.toString(str));
}

Reflection and runtime class to get method

Actually in all my class, i alway have attribute name
Class clazz, Object obj
When we know the object type, we can do something like (if id is a attribute....)
Integer id = ((BaseObj) field.get(obj)).getId();
Actually
field.get(obj))
return me a object, i search to get value of name attribute of this object.
I search to do something like
String name = ((clazz.getClass()) field.get(obj)).getName();
You cannot cast to a class that's only known at runtime. Either make all these classes implement an interface with a getName() method or you'll have to resort to reflection:
String name = (String) clazz.getMethod("getName").invoke(obj);

Convert Field Type to the corresponding instance type

I have a class, in which I have a field called say batman
String batman
And I have method in this class, which does the following:
for(Field field : obj.getClass().getFields()) {
if(field.getName().equals(fieldName)) // here fieldName is batman
//now need to call Strings method like split etc
}
I need to convert the field to String and call methods. Is it possible to do so?
Thanks in advance.
First of all u can use Field batmanField = obj.getClass().getDeclaredField(fieldName); instead foreach. For get field value u can use String batmanValue = batmanField.get(obj);
You can use the Field#get(Object obj) method to get the value of the field represented by the Field you are working with, on the specified object obj.
if (field.getName().equals(fieldName)) {
String batmanValue = (String) field.get(obj);
..
}
This will give you the value of the batman field. Then you can use the String specific methods.

Custom 'String' Class

I'm trying to figure out how java classes work.
When I create a StringBuilder:
StringBuilder testString = new StringBuilder("Hello World!);
If I want to, say, get the value that testSting holds a reference to, I can simply call it like: System.out.println(testString);
This is cool behavior, but I'm unsure how to replicate it in classes that I make.
For instance, if I were to try and re-implement my own version of StringBuilder, the approach I would take (as a beginner), would be this:
class MyBuilder {
char[] string;
public MyBuilder(String s) {
string = new char[s.length()];
string = s.toCharArray();
}
So, to make the string an array I had to store it in a data field of the class. But then, to access this in my code, I can't print it by simply calling the variable name. I would have to use .property syntax. Thus, to duplicate the above example, I would have to type System.out.println(testString.value); Which isn't nearly as pretty.
How do you make a class such that it behaves like String or StringBuilder and returns its value without manually accessing the data fields?
Implement a toString method.
toString is a method on Object, so every java object inherits one. The default implementation that you inherit is only useful for getting the class type, and for distinguishing one object from another; the format is: ClassName#HashCode. There are no details unique to your implementation.
In your own classes, to get the description that you want you'll need to override the toString method, so that in contexts where a String is expected, e.g. when you call System.out.println(myObject.toString());, your own format is used.
It's often a good idea to do this, for a more readable description of your object. You can always call super.toString to include the output from the default - ClassName#HashCode - in your own output.
You can override Object.toString() in your object MyBuilder. System.out.println calls on this method for every object used. For example here, you could use:
#Override
public String toString() {
return Arrays.toString(string);
}
Overwrite the toString-Method
private String value;
public MyClass(String value) {
this.value = value;
}
public String toString() {
return value;
}

Categories