使用反射获取类的成员(字段,属性)

版权声明:本文为博主原创文章,请随意转载。 https://blog.csdn.net/sy755754582/article/details/88186371
public class getFie {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        Class<?> aClass = Class.forName("com.zhiyou100.refle.Phone");
        //只能调用public 字段,但是能得到父类的字段
        Field[] fields = aClass.getFields();
        for (Field f:fields
             ) {
           //System.out.println(f);
        }
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field f:declaredFields
             ) {
            //System.out.println(f);
        }
        //得到字段的数据类型
        Field name = aClass.getField("name");
        String name1 = name.getType().getName();
        System.out.println(name1);
        String simpleName = name.getType().getSimpleName();
        System.out.println(simpleName);
        //
        Field price = aClass.getDeclaredField("price");
        System.out.println(price.getType().getSimpleName());
        price.setAccessible(true);
        Object o = aClass.newInstance();
        price.set(o,2999);
        System.out.println(price.get(o));

猜你喜欢

转载自blog.csdn.net/sy755754582/article/details/88186371