A problem occurs during project creation, that is, the class needs to be dynamically loaded and the object needs to be instantiated. Now let's share it with you!
In addition, class. forname (""). newinstance (); is really good for factories. You can try it when it comes to use!
The purpose of the class. forname () static method is to dynamically load classes. After loading, you must call the newinstance () static method under the class to instantiate the object for operation. Therefore, it is useless to use class. forname () alone to dynamically load classes. The ultimate goal is to instantiate objects.
UpperCodeSaid:
First, the parent code:
1 PackageCom. Test. entity;2 3 Public ClassItembase {4PublicString tostring (){5Return"Itembae";6 }78}
Subclass code:
Package Com. Test. entity; Public Class Itema Extends Itembase { Private String name; Private String age; @ override Public String tostring (){ Return "A's name:" + name + ", A's age:" + Age ;} Public String getname (){ Return Name ;} Public Void Setname (string name ){ This . Name = Name ;} Public String getage (){ Return Age ;} Public Void Setage (string age ){ This . Age =Age ;}}
Package Com. Test. entity; Public Class Itemb Extends Itembase { Private String name; Private String age; @ override Public String tostring (){ Return "B's name:" + name + ", B's age:" + Age ;} Public String getname (){ Return Name ;} Public Void Setname (string name ){ This . Name = Name ;} Public String getage (){ Return Age ;} Public Void Setage (string age ){ This . Age = Age ;}}
Factory Code:
PackageCom. Test. factory;ImportCom. entity. Test. entity. itembase;Public ClassFactory {Public StaticItembase createobj (string classname)ThrowsException {Return(Itembase) class. forname (classname). newinstance ();}
Usage
Public ClassTest {Public Static VoidMain (string [] ARGs) {itembase= (Itembase) Factory. createobj ("com. Test. entity. itema"); System. Out. println ("A:" +Itembase. tostring (); itembase= (Itembase) Factory. createobj ("com. Test. entity. itemb"); System. Out. println ("B" +Itembase. tostring ());}}
Here is just an example. You can configure your class to XML for dynamic reading. You only need to modify the XML to get the class you want '~ Many usage '~ I'm just a simple demonstration.