Reflection and runtime class to get method - java

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);

Related

Get Class Name for the given String

I have a use case, where I have stored the List of Java Data Types in DB, Like Byte, Character, Integer, Long, BigDecimal, BigInteger, Boolean.
So my use case is like If I read the value Long, I need to create the Long.class, if I read String, then String.class.
Class cls = Class.forName("java.lang.Long);, then I can use the cls for my own purpose.
I can achieve this, by having Enum of the above data types, as soon I read the value from the db, I pass the value to enum to get the class type. But I don't know whether it is efficient or not. Is there any method present in Java which gives like, for the given string,(without fully qualified name), it should return the class type.
Storing a reference to the Class object is efficient but using the Class object for reflection can be expensive. If you're just using the Class for reference then you're fine.
enum Decodable {
BIG_INTEGER(BigInteger.class),
INTEGER(Integer.class)
// etc
private final Class<?> decodableClass;
private Decodable(Class<?> decodableClass) {
this.decodableClass = decodableClass;
}
}
You could also just maintain a Set of Class objects.
private static final Set<Class<?>> DECODABLE_CLASSES = ImmutableSet.of(Integer.class, BigInteger.class); //etc

How to access dynamiclly variables from another Java Class?

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

difference between 'Class<?>' and 'Object' as argument of method

Assume i want to have a method that get an object of any type in my application to validate all fields it has (each object has different fields with different types) and wrap it to a message. so the method input argument would be instance of any object
Now my question is :
what's the difference between having this input argument as an Object or Class<?> ?
as i know ? means 'any type or class' and 'Object' is a super type in java .
i appreciate if Someone could explain me in which cases better to use this :
public validateAndConvertAnyObject(Object obj) {
// compute and return a message
}
and when it's better to use this ?
public validateAndConvertAnyObject(Class<?> obj) {
// compute and return a message
}
First you don't specify a return type in your method.
It is not valid.
Second, these two parameters are totally different.
public validateAndConvertAnyObject(Object obj)
can accept any object.
While public validateAndConvertAnyObject(Class<?> obj)
can accept any class.
The equivalent of
public validateAndConvertAnyObject(Object obj)
with generic would be :
public <T> void validateAndConvertAnyObject(T obj){
After compilation and type erasure, these provide the same compiled class.
So in this example, using Object makes more sense as more explicit.
To convert an instance to another class with reflection, generally, you pass the target class :
public <T> T validateAndConvertAnyObject(Object obj, Class<T> targetClass){
...//processing on obj
}
And you could use it :
MyObject myObject = ...;
MyOtherClass myOtherClass = validateAndConvertAnyObject(myObject, MyOtherClass.class);
The first method can be called with any object as an argument, eg "foo", 42 or Integer.class. The second one will only accept class objects, eg "foo".getClass() or String.class
What is the difference between Class<?> and Object
Object
This takes the instance as a parameter
Class<?>
This takes a class as a parameter
Example
Object could be equal to String, and for a similar result you could have Class<?> equal to java.lang.String.
Confusion
Technically, you could pass an instance of Class<?> as an Object, which adds confusion, which is a good reason to use Class<?> instead, as it prevents mixing up the instance and it's class.
Object actually represents an instance of a created object like:
String text = "Hello World!";
Object textAsObj = (Object) text;
Whereas Class only represents the class of objects, it has no connection to an actual instance of this class:
Class<?> textClass = Class.forName("java.util.String");
So you should probably use the Object variant if you want to access specific values of an instance. You can, at anytime, retrieve the class from an Object using the getClass method:
String text = "Hello World!";
Class<String> textClass = text.getClass();
And here is an example how you could use that to access a field of a given Object:
Person person = new Person("John Doe");
Class<Person> personClass = person.getClass();
Field nameField = personClass.getDeclaredField("name");
String name = (String) nameField.get(person);

Get Thrift Field Type from ID

Is there a way to get the type of a parameter using the thrift ID? I have data coming in that needs to go to one of 6 different Thrift objects so I'm using reflection to instantiate the appropriate object and set data fields.
Class<?> cls = Class.forName(package + table.name);
Object o = cls.newInstance();
Method getField = cls.getMethod("fieldForId", int.class);
Object field = getField.invoke(o, thriftId);
Method setField = cls.getMethod("setFieldValue", field.getClass(), Object.class);
setField.invoke(o, field, data);
The variable data is a String. This code works great until it comes across a field with a type other than String where I can get ClassCastException. I tried doing this:
Method getFieldValue = cls.getMethod("getFieldValue", field.getClass());
System.out.println(getFieldValue.invoke(o, field).getClass.getName());
But for String, getFieldValue returns null if they are blank and you can't get the class. I could assume that all null values are Strings, but that seems dangerous considering Lists, Maps, etc are probably returned as null as well.
I also tried getting the Class of the field but it just comes back as the Enum (_Fields) which is expected.
I managed to find a solution. Grab the name of the field then get that field.
Method getFieldName = field.getClass().getMethod("getFieldName");
String fieldName = (String) getFieldName.invoke(field);
Class<?> fieldType = cls.getField(fieldName).getType());

Indicate datatype from a input string?

For example i have a string input "int",can i declare a variable base on that input?
(Not switch check please). I mean something like this (pseudo-code) or similar:
String str="int";
new (variable_name,"int");
// create new variable with int datatype.
You can do this:
String className = "MyClass";
Object obj = Class.forName(className).newInstance();
But it won't work for primitive types.
If instead of using primitive types you will use cannonical name of Object based class you can try to do this
public Object loadClass(String className) {
return Class.forName(className).newInstance(); //this throw some exceptions.
}
Not practically, Java is strongly typed and the type of all variables must be known at compile time if you are to do anything useful with them.
For example, you could do something like this;
String str = "java.lang.Integer";
Class clazz = Class.forName(str);
Object o = clazz.newInstance();
..which will give you an Object o whose type is determined at runtime by the value of the String str. You can't do anything useful with it though without first casting it to the actual type, which must be known at compile time.

Categories