0

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();
1
  • That cannot possibly work, since the compiler still wouldn't know that getName() exists. Commented Nov 16, 2017 at 16:48

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.