簡體   English   中英

如何從私有靜態內部類訪問變量

[英]How to access variables from private static inner class

我有一個這樣的類結構:

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
        }
    }
}

我在程序中得到一個外部對象,如何使用反射在程序中提取innerPersonal

當您要執行的外部代碼Outer ,您不能使用Outer.Inner.class參閱您的static inner class ,因為它是private的,所以這里我提出一個辦法,只會讓該領域的第一個值personal ,然后調用最終返回此inner class的字段的返回值(假定它不為null getClass()上的getClass() ,該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);

也許這可行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM