Python equivalent of getattr?

I am converting python code to java and have a situation where I need to call the methods of an object but don’t know which methods are before execution. In python, I resolve this by using getattr on my object and passing it a string, which is the name of my method. How would you do something like this in Java?

+8
java python reflection
source share
6 answers

Class.getField is your friend. This will probably not be very simple, since Python is dynamically typed, and Java is statically typed (unless you know your field types in advance.)

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

Attribute Search

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 simpler cases, you need to know if you have a field or method. esp because they can have the same name. In addition, methods can be overloaded, so you need to know what method signature you want.

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

+12
source share

You can start here to learn about Java Reflection.

0
source share

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

0
source share

In Java, you do this using the Reflection API (and it's usually rather cumbersome).

MethodUtils in the Apache Commons BeanUtils project can work with it a little easier, although this is a pretty heavy dependency for something simple like that.

0
source share

You must use the Reflection API . Since the pure API is a little ... impregnable, you should take a look at helpers such as commons beanutils or reflections .

0
source share

The easiest way to handle this is to create a Map object in the Java class and continue to add name-value pairs and retrieve it appropriately, although it may not support the various types that setAttr supports.

0
source share

Source: https://habr.com/ru/post/649984/


All Articles