简体   繁体   中英

How to access variables from private static inner class

I've a class structure like this:

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

I get an object of Outer in my program, How can I extract innerPersonal in my program, using reflection.

As you want to execute the code outside Outer , you cannot use Outer.Inner.class to refer to your static inner class as it is private , so here I propose an approach that will simply get first the value of the field personal , then call getClass() on the returned value of the field (assuming that it is not null ) to finally access to this inner class which allows to access also to its field 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);

maybe this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM