Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is Spring BeanFactory able to instantiate a non-public class?

Spring newbie here.

I observed that Spring was able to instantiate a non-public class (i.e. a class with default visibility) that I had defined. Can anyone tell me how Spring achieves this? Why is this allowed ?

like image 206
Rahul Avatar asked Mar 25 '11 09:03

Rahul


1 Answers

OK, here's how they do it. Take this sample class:

package hidden;  

class YouCantInstantiateMe{

    private YouCantInstantiateMe(){
        System.out.println("Damn, you did it!!!");
    }

}

The above is a package-private class with a private constructor in a different package, but we'll still instantiate it:

Code (run from a class in a different package):

public static void main(final String[] args) throws Exception{
    Class<?> clazz = Class.forName("hidden.YouCantInstantiateMe");
                                            // load class by name
    Constructor<?> defaultConstructor = clazz.getDeclaredConstructor();
    // getDeclaredConstructor(paramTypes) finds constructors with
    // all visibility levels, we supply no param types to get the default
    // constructor
    defaultConstructor.setAccessible(true); // set visibility to public
    defaultConstructor.newInstance();       // instantiate the class
}

Output:

Damn, you did it!!!


Of course what Spring does is much more complex, because they also deal with Constructor Injection etc., but this is how to instantiate invisible classes (or invisible constructors).

like image 105
Sean Patrick Floyd Avatar answered Oct 07 '22 21:10

Sean Patrick Floyd