通过反射,如何获得子类继承自父类的属性

通过反射,如何获得子类继承自父类的属性,第1张

你是想通过反射获得该类所有属性值或是给所有属性赋值吧。用getMethods获取所有的getter和setter方法,再取值或赋值。但不要用getDeclaredMethods,因为getMethods反映此 Class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共 member 方法;而getDeclaredMethods反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。

这也许是框架注入属性值都采用setter注入的原因吧。

你的意思就是要获取内部类的属性和方法喽?

Class classes[]=clazzgetDeclaredClasses();//返回类包含的全部内部类

然后再进行处理呗。

Class clazz=XXgetClass();

Class classes[]=clazzgetDeclaredClasses();

for(Class c:classes){//对成员内部类进行反射

int i=cgetModifiers();

String s=ModifiertoString(i);

if(scontains("static"))//静态内部类的处理

cgetConstructor()newInstance();

else//实例内部类的处理

cgetConstructor(ricgetClass())newInstance(ric);

}

//由于匿名内部类没有构建器,因此无法创建实例,也无法直接访问其中的方法,但可以通过下面的方式巧秒的执行其中的方法或成员变量。

Runnable r=(Runnable)(clazzgetField("ta")get(ric));

rrun();

Class<> obj=ClassforName(refgetClass()getName());

Object object = objnewInstance();

Method method=objgetMethod("getLength");

你这样拿到的是你newInstance新构建的对象,又不是你之前设定了值的对象,域当然会是0

应该是这样:methodinvoke(ref)

先获取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;

    }

}

以上就是关于通过反射,如何获得子类继承自父类的属性全部的内容,包括:通过反射,如何获得子类继承自父类的属性、JAVA 反射获取的属性是复合类型、怎样通过反射获得一个类的属性值或者方法返回值等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

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

原文地址:https://54852.com/web/9431083.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存