The dynamically changed classes are as follows:
Public class ScrollImage implements Face {
Private static String TEST = "TEST ";
Public static void change (String change ){
TEST = change;
}
Public void myFace (String describe ){
}
/**
* Constructor for ScrollImage.
*/
Public ScrollImage (){
Super ();
System. out. println (":)" + TEST );
Show ();
}
...
Note:When new ScrollImage () is used, the output is: :)) TEST.
My goal is to change its output through class loading. It actually changes the value of a static constant, which is also equivalent to changing the reference value of any instance for this constant.
First, determine whether the class is the class we need to change dynamically.
Class cImage;
Object oImage;
MyLoader loader = new MyLoader ();
CImage =
Loader. load ("ScrollImage. class", "cn.com. efly. swt. ScrollImage ");
If (Face. class. isAssignableFrom (cImage ))
System. out. println (":):)");
Change it:
String arg = "changed ";
/** You can also directly access the constant to change it, but you need to modify the visible CONSTANTPublic
* My ClassLoader:
* Public class MyLoader extends ClassLoader {
* Static int maxsize = 10000;
* Public Class load (String namefile, String classname)
* Throws java. lang. Exception {
* Try {
* // Determine whether the class has been transferred in. If yes, it will be returned directly. Otherwise, it will be called in.
* Class ctmp = this. findLoadedClass (classname );
* System. out. println (ctmp. getName () + "is load ");
* Return ctmp;
*} Catch (Exception e ){
* // System. out. println (e );
*}
* Java. io. FileInputStream in = new java. io. FileInputStream (namefile );
* Byte [] classbyte = new byte [maxsize];
* // Encryption and decryption can be performed on a file in actual application, as long as * defineClass is used
* // Decrypted content.
* Int readsize;
* Readsize = in. read (classbyte );
* // System. out. println ("Read File length:" + readsize );
* In. close ();
* Return defineClass (classname, classbyte, 0, readsize );
*}
*}
*/
// CImage. getField ("TEST"). set (null, "Changed ");
Java. lang. reflect. Method change =
CImage. getMethod ("change", new Class [] {String. class });
Change. invoke (change, new Object [] {arg });
Instantiate this class and you can see the result:
OImage = cImage. newInstance ();
Result output:
:):)
:)) Changed
Conclusion: The method can be used to solve some special problems, but I do not encourage you to use it. In my new design, I have not considered using the change method. It has no benefits for the structure.