我有一个这样的类结构:
public class Outer{
private Outer.Inner personal;
public Outer(){
//processing.
//personal assigned value
}
........
private static class Inner {
private final Set<String> innerPersonal;
Inner(){
innerPersonal=new HashSet<>();
//populate innerPersonal
}
}
}
我在程序中得到一个Outer对象,我如何提取innerPersonal在我的程序,使用反射。
当你想在Outer
之外执行代码时,你不能使用Outer.Inner.class
来引用你的static inner class
,因为它是private
,所以在这里我提出一种方法,它将简单地首先获得字段personal
的值,然后在字段的返回值上调用getClass()
(假设它不是null
)最终访问这个inner class
,它允许访问它的字段innerPersonal
。
Outer outer = ...
// Get the declared (private) field personal from the public class Outer
Field personalField = Outer.class.getDeclaredField("personal");
// Make it accessible otherwise you won't be able to get the value as it is private
personalField.setAccessible(true);
// Get the value of the field in case of the instance outer
Object personal = personalField.get(outer);
// Get the declared (private) field innerPersonal from the private static class Inner
Field innerPersonalField = personal.getClass().getDeclaredField("innerPersonal");
// Make it accessible otherwise you won't be able to get the value as it is private
innerPersonalField.setAccessible(true);
// Get the value of the field in case of the instance personal
Set<String> innerPersonal = (Set<String>)innerPersonalField.get(personal);
@Retention(RetentionPolicy.RUNTIME)
public @interface Factory {
Class<?> value();
}
public class Outer{
private Outer.Inner personal;
public Outer(){
//processing.
//personal assigned value
}
@Factory(SomeType.class)
private static class Inner {
public final Set<String> innerPersonal;
Inner(){
innerPersonal=new HashSet<>();
//populate innerPersonal
}
}
}
Outer o = new Outer();
Object r = o.getClass().getAnnotationsByType(Factory.class);