开发者

Java equivalent of python's getattr?

开发者 https://www.devze.com 2023-01-29 22:22 出处:网络
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

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?


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.


You can start here to learn about Java Reflection.


You can use java reflection but there is no exact equivalent of getattr.


In Java you do this with the Reflection API (and it's usually pretty cumbersome).

MethodUtils in Apache Commons BeanUtils project may make it a bit easier to work with, though it's a pretty hefty dependency for something simple like this.


You should use the Reflection API. Since the pure API is a bit ... unapproachable, you should have a look at helpers like commons beanutils or reflections.


The easiest way to handle this is to create a Map object in Java class & keep adding the name value pairs & retrieve it accordingly though it might not support different types that setAttr supports.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号