How can Spring BeanFactory instantiate a non-public class?

Spring is new here.

I noticed that Spring was able to create an instance of a non-public class (i.e. the class with default visibility) that I defined. Can someone tell me how Spring achieves this? Why is this allowed?

+6
java spring class-visibility
source share
2 answers

OK, that’s how they do it. Take this sample class:

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

The above package is a private class with a private constructor in another package, but we will create it anyway:

Code (executed from a class in another 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, which makes Spring a lot more complicated, because they also deal with design injection, etc., but this is how to create invisible classes (or invisible constructors).

+19
source share

The one who is responsible for checking whether you (or Spring) are allowed to instantiate the class at runtime is Security Manager . If you're working with a simple main class, you probably don't have one at all. If you configure the application to run using the Security Manager and do not grant Spring special permissions, it will not be able to instantiate non-public classes.

+11
source share

All Articles