When learning the Spring Framework base bean package, a simple example is written, similar to the following:
Package Study.spring.bean;
public class Simplebean
{
Private String Beanname;
Private Simplebean () {
System.out.println ("Simplebean");
}
/** */ /**
* @return Returns the beanname.
*/
Public String Getbeanname ()
{
return beanname;
}
/** */ /**
* @param beanname the beanname to set.
*/
public void Setbeanname (String beanname)
{
this. Beanname = Beanname;
}
}
It was surprising that the reflection mechanism was often used in previous projects, but it was not possible to construct classes that had only private constructors.
Make a simple example of yourself:
Package Study.spring.bean;
Import Java.lang.reflect.Constructor;
Import java.lang.reflect.InvocationTargetException;
public class SimpleTest
{
/** *//**
* @param args
*/
public static void Main (string[] args)
{
TODO auto-generated Method Stub
Try
{
Constructor[] Cts=class.forname ("Study.spring.bean.SimpleBean"). Getdeclaredconstructors ();
for (int i=0;i<cts.length;i++) {
Cts[i].newinstance (NULL);
}
}
catch (SecurityException e)
{
TODO auto-generated Catch block
E.printstacktrace ();
}
catch (ClassNotFoundException e)
{
TODO auto-generated Catch block
E.printstacktrace ();
}
catch (IllegalArgumentException E)
{
TODO auto-generated Catch block
E.printstacktrace ();
}
catch (Instantiationexception e)
{
TODO auto-generated Catch block
E.printstacktrace ();
}
catch (Illegalaccessexception e)
{
TODO auto-generated Catch block
E.printstacktrace ();
}
catch (InvocationTargetException e)
{
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Also, as I was trying to throw a java.lang.IllegalAccessException exception, I wondered if the spring framework used some of the features of reflection, and then looked at the relevant documentation to see why:
In fact, when Java creates an instance of a class by default, it detects whether the security is relevant and the detection switch can be turned off.
Constructor, Field, and method are all inherited from AccessibleObject, and the corresponding instance calls Setaccessible (true) to turn off the switch
As in the above example, the code cts[i].newinstance (null); This method is called before the line: Cts[i].setaccessible (TRUE);
This allows you to create only instances of constructors, invoke private constructor methods, and access private properties of the class.
Oh, it seems that Java security is greatly reduced. If you are very focused on the security of the application, Java of course take this into account, and you can add-djava.security.manager to the JVM startup parameter to enable the security manager, if you have this parameter, It will detect if the code that is shutting down access detection is allowed to do so, and the above code throws a Java.security.AccessControlException exception when executed.