如何在java中动态读取对象属性?

2022-09-03 17:53:41

有没有办法动态读取和打印对象属性(Java)?例如,如果我有以下对象

public class A{
  int age ;
  String name;
  float income;

}

public class B{
 int age;
 String name;
}

public class mainA{
   A obj1 = new A();
   method(A);
   method(B); 
}

the output should be like

While running method(A):
Attribute of Object are age,name,income;
While executing method(B):
Attribute of Objects are age,name;

我的问题是,我可以在formula()中传递各种对象,是否有任何方法可以访问不同对象的属性。


答案 1

您想要使用反射 API。具体来说,看看如何发现类成员

您可以执行类似操作:

public void showFields(Object o) {
   Class<?> clazz = o.getClass();

   for(Field field : clazz.getDeclaredFields()) {
       //you can also use .toGenericString() instead of .getName(). This will
       //give you the type information as well.

       System.out.println(field.getName());
   }
}

我只是想补充一个警告,你通常不需要做这样的事情,对于大多数事情,你可能不应该这样做。反射会使代码难以维护和读取。当然,在一些特定情况下,你会想要使用反射,但这些情况相对较少见。


答案 2

使用我们可以做到这一点。如果为 bean 定义了正确的 getter 和 setter,我们还可以动态设置该值:org.apache.commons.beanutils.PropertyUtils

import org.apache.commons.beanutils.PropertyUtils;
import java.beans.PropertyDescriptor;

public class PropertyDescriptorTest {

    public static void main(String[] args) {

        // Declaring and setting values on the object
        AnyObject anObject = new AnyObject();
        anObject.setIntProperty(1);
        anObject.setLongProperty(234L);
        anObject.setStrProperty("string value");

        // Getting the PropertyDescriptors for the object
        PropertyDescriptor[] objDescriptors = PropertyUtils.getPropertyDescriptors(anObject);

        // Iterating through each of the PropertyDescriptors
        for (PropertyDescriptor objDescriptor : objDescriptors) {
            try {
                String propertyName = objDescriptor.getName();
                Object propType = PropertyUtils.getPropertyType(anObject, propertyName);
                Object propValue = PropertyUtils.getProperty(anObject, propertyName);

                // Printing the details
                System.out.println("Property="+propertyName+", Type="+propType+", Value="+propValue);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}

设置特定属性的值:

// Here we have to make sure the value is
// of the same type as propertyName
PropertyUtils.setProperty(anObject, propertyName, value);

输出将为:

Property=class, Type=class java.lang.Class, Value=class genericTester.AnyObject
Property=intProperty, Type=int, Value=1
Property=longProperty, Type=class java.lang.Long, Value=234
Property=strProperty, Type=class java.lang.String, Value=string value