robert trudel
robert trudel

Reputation: 5749

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

Upvotes: 0

Views: 28

Answers (1)

f1sh
f1sh

Reputation: 11934

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

Upvotes: 1

Related Questions