When studying the source of the enum class, trace the following code to the class:
t[] getenumconstantsshared () {if(Enumconstants = =NULL) { if(!isenum ())return NULL; Try { FinalMethod values = GetMethod ("Values"); java.security.AccessController.doPrivileged ( New Java.security.privilegedaction<void> () {public Void run () { Values.setaccessible (TRUE); return null; } }); Enumconstants= (t[]) Values.invoke (NULL); } //These can happen when users concoct enum-like classes//That's don ' t comply with the enum spec. Catch(InvocationTargetException ex) {return NULL; } Catch(Nosuchmethodexception ex) {return NULL; } Catch(Illegalaccessexception ex) {return NULL; } } returnenumconstants; } Private volatile transientt[] Enumconstants =NULL;
There are two red codes in the above code:
1. Java.security.AccessController.doPrivileged ... This code can be consulted: "Thread collaboration based on the Java 2 runtime security Model" http://www.ibm.com/developerworks/cn/java/j-lo-rtsecurity/
Unfortunately read again or dizzy vegetables, what must be signed and so on, usually did not meet Ah, Khan AH ~ ~ ~
2, volatile is to solve the problem of thread visibility, transient is a temporary variable will not be serialized.
Refer to the following code for the transient problem:
Packagecom.study.java.core.serializable;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.InputStream;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;ImportJava.io.OutputStream;Importjava.io.Serializable;ImportCom.study.java.core.Employee; Public classPersonImplementsserializable{Private transientEmployee employee=NULL; PrivateString id=NULL; Private transientString pwd=NULL; PublicPerson (Employee employee) { This. employee=employee; } PublicString getId () {returnID; } Public voidsetId (String id) { This. ID =ID; } PublicString getpwd () {returnpwd; } Public voidsetpwd (String pwd) { This. PWD =pwd; } @Override PublicString toString () {return This. GetClass (). GetName () + ": id=" +id+ ", pwd=" +pwd+ ", Employee:" +employee; } Public Static voidMain (string[] args) {Employee Employee=NewEmployee (); Employee.setid ("Staff 1"); Employee.setname ("Employee Name"); Person Person=NewPerson (employee); Person.setid ("001"); Person.setpwd ("Password"); Try{outputstream OS=NewFileOutputStream ("F:" +file.separator+ "A.txt"); ObjectOutputStream Oos=Newobjectoutputstream (OS); Oos.writeobject (person); Oos.flush (); Oos.close (); InputStream is=NewFileInputStream ("F:" +file.separator+ "A.txt"); ObjectInputStream Ois=NewObjectInputStream (IS); Person Person1=(person) ois.readobject (); System.out.println (Person1.tostring ()); } Catch(Exception e) {//Todo:handle Exception } }}
As can be seen from the output: both PWD and employee are NULL because they are set to transient
Java security Model (sandbox or policy) and transient variables