sidd.v29
sidd.v29

Reputation: 83

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.

Upvotes: 1

Views: 1197

Answers (2)

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

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);

Upvotes: 2

FreeMan
FreeMan

Reputation: 1457

@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.

Upvotes: 0

Related Questions