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

Mik*_*ike 11 java core object

有没有办法动态地读取和打印对象属性(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;
Run Code Online (Sandbox Code Playgroud)

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

Viv*_*ath 15

您想使用The Reflection 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());
   }
}
Run Code Online (Sandbox Code Playgroud)

我只是想添加一个注意事项,你通常不需要做这样的事情,对于你可能不应该做的大多数事情.反射可以使代码难以维护和阅读.当然,有些特定情况需要使用Reflection,但这些情况相对较少.


小智 7

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

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();
            }
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

要设置特定属性的值:

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

输出将是:

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();
            }
        }

    }

}
Run Code Online (Sandbox Code Playgroud)