Search code examples
javaclassreflectionpackage-private

Accessing non-visible classes with reflection


I am trying to get an instance of a non-visible class, AKA package private class, using reflection. I was wondering if there was a way to switch the modifiers to make it public and then access it using Class.forName. When I try that now it stops me saying I can't do it. Unfortunately there is no setAccesible method of the Class class.


Solution

  • nested class - class defined within other class (includes static and non-static classes)
    inner class - non-static nested class (instance of inner class can only be created via instance of outer class)

    non-nested (top level) classes

    Based on your question we know that constructor you want to access is not public. So your class may look like this (A class is in some package different than ours)

    package package1;
    
    public class A {
        A(){
            System.out.println("this is non-public constructor");
        }
    }
    

    To create instance of this class we need to get to constructor we want to invoke, and make it accessible. When it is done we can use Constructor#newInstance(arguments) to create instance.

    Class<?> c = Class.forName("package1.A");
    //full package name --------^^^^^^^^^^
    //or simpler without Class.forName:
    //Class<package1.A> c = package1.A.class;
    
    //In our case we need to use
    Constructor<?> constructor = c.getDeclaredConstructor();
    //note: getConstructor() can return only public constructors
    //so we needed to search for any Declared constructor
    
    //now we need to make this constructor accessible
    constructor.setAccessible(true);//ABRACADABRA!
    
    Object o = constructor.newInstance();
    

    nested and inner classes

    If you want to access nested (static and non-static) Class with Class.forName you need to use syntax:

    Class<?> clazz = Class.forName("package1.Outer$Nested");
    

    Outer$Nested says that Nested class is declared within Outer class. Nested classes are very similar to methods, they have access to all members of its outer class (including private ones).

    But we need to remember that instance of inner class to exists requires instance of its outer class. Normally we create them via:

    Outer outer = new Outer();
    Outer.Inner inner = outer.new Inner();
    

    so as you see each instance of Inner class have some information about its outer class (reference to that outer instance is stored in this$0 field, more info: What does it mean if a variable has the name "this$0" in IntelliJ IDEA while debugging Java?)

    So while creating instance of Inner class with Constructor#newInstance() you need to pass as first argument reference to instance of Outer class (to simulate outer.new Inner() behavior).

    Here is an example.

    in package1

    package package1;
    
    public class Outer {
        class Inner{
            Inner(){
                System.out.println("non-public constructor of inner class");
            }
        }
    }
    

    in package2

    package package2;
    
    import package1.Outer;
    import java.lang.reflect.Constructor;
    
    public class Test {
        public static void main(String[] args) throws Exception {
    
            Outer outerObject = new Outer();
    
            Class<?> innerClazz = Class.forName("package1.Outer$Inner");
    
            // constructor of inner class as first argument need instance of
            // Outer class, so we need to select such constructor
            Constructor<?> constructor = innerClazz.getDeclaredConstructor(Outer.class);
    
            //we need to make constructor accessible 
            constructor.setAccessible(true);
    
            //and pass instance of Outer class as first argument
            Object o = constructor.newInstance(outerObject);
            
            System.out.println("we created object of class: "+o.getClass().getName());
    
        }
    }
    

    static-nested classes

    Instances of static-nested classes don't require instance of Outer class (since they are static). So in their case we don't need to look for constructor with Outer.class as first argument. And we don't need to pass instance of outer class as first argument. In other words code will be same as for non-nested (top-level) class (maybe except the fact that you would need to add use $ instead of . in class name to when referring to nested classes in Class.forName() like Class.forName("some.package.Outer$Nested1$NestedNested")).