如何利用java反射,获取属性接口的具体类

我有一个类,但是该类里面有一个接口的属性,现在是想通过反射获取一个实现该接口的实例,即获取一个a,并且这个a的body已经是我指定的接口实现类的,请问怎么实现?
class a{
Body body;
}
interface Body{
}

class BodyImpl{
//do something
}

你可以这么写:
class BodyImpl implements Body{
//do something
public static void main(String[] args) {
Type[] interfaces = BodyImpl.class.getInterfaces();
ParameterizedType firstInterface = (ParameterizedType) interfaces[0];
Class c = (Class) firstInterface.getActualTypeArguments()[0];
System.out.println(c.getName()); // prints "AtomEntry"
}
}

就得到你所要的接口参数了!追问

谢谢你的回答,不过你误解我意思了,我是想通过Class a获取一个由它自身body属性实现body接口的实例,不是想得body的接口

温馨提示:内容为网友见解,仅供参考
第1个回答  2021-03-28

Java反射-属性操作

相似回答