Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of python's getattr?

I'm converting some python code to java, and have a situation where I need to call methods of an object but don't know which methods until runtime. In python I resolve this by using getattr on my object and passing it a string that is the name of my method. How would you do something similar in Java?

like image 314
Johnny Avatar asked Dec 09 '10 12:12

Johnny


1 Answers

Class.getField is your friend. It probably won't be very straightforward though since Python is dynamically typed and Java is statically typed (unless you know the types of your fields in advance.)

EDIT: How to translate these examples. http://effbot.org/zone/python-getattr.htm

Attribute Lookup

Python

//normal
value = obj.attribute

//runtime
value = getattr(obj, "attribute")

Java

//normal
value = obj.attribute;

//runtime
value = obj.getClass().getField("attribute").get(obj);


Method Call

Python

//normal
result = obj.method(args)

//runtime 
func = getattr(obj, "method")
result = func(args)

Java

//normal
result = obj.method(args);

//runtime
Method func = obj.getClass().getMethod("method", Object[].class);
result = func.invoke(obj, args);

In the simpler cases, you need to know whether you have a field or a method. esp as they can have the same name. Additionally methods can be overloaded, so you need to know which method signature you want.

If you don't care which method or field you get, you can implement this as a helper method fairly easily.

like image 178
NPE Avatar answered Sep 22 '22 05:09

NPE