如何通过Java反射获取一个类属性的类型要类型Class<

如何通过Java反射获取一个类属性的类型要类型Class<,第1张

先获取Method对象

以下仅供参考

package comkiddtestzhidao;

import javalangreflectMethod;

/

  Hello world!

 

 /

public class Main {

    public static void main(String[] args) {

        Method method1 = null;

        Method method2 = null;

        try {

            method1 = ClassforName("comkiddtestzhidaoCat")getMethod("getName", (Class<>[]) null);

            method2 = ClassforName("comkiddtestzhidaoCat")getMethod("getChilds", (Class<>[]) null);

        } catch (NoSuchMethodException ex) {

            exprintStackTrace();

        } catch (SecurityException ex) {

            exprintStackTrace();

        } catch (ClassNotFoundException ex) {

            exprintStackTrace();

        }

        if (null != method1) {

            Systemoutprintln(method1getGenericReturnType()getTypeName());

        }

        if (null != method2) {

            Systemoutprintln(method2getGenericReturnType()getTypeName());

        }

    }

}

class Cat {

    private String name;

    private Cat[] childs;

    public String getName() {

        return name;

    }

    public void setName(String name) {

        thisname = name;

    }

    public Cat[] getChilds() {

        return childs;

    }

    public void setChilds(Cat[] childs) {

        thischilds = childs;

    }

}

public class Student{

    private static int age;

}

   Field field = StudentclassgetDeclaredField("age");

    fieldsetAccessible(true);

    fieldget(null);     普通属性获取值 需要传入对象,但是静态属性 不需要传入具体对象,传

null 也可以获取 该字段的值。

以上就是关于如何通过Java反射获取一个类属性的类型要类型Class<全部的内容,包括:如何通过Java反射获取一个类属性的类型要类型Class<、反射--静态成员变量的值获取、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/9653235.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-30
下一篇 2023-04-30

发表评论

登录后才能评论

评论列表(0条)

保存