Static methods for dynamically executing classes in Java

Source: Internet
Author: User

In Java, the Class.forName () method enables you to dynamically decide which class to load, which is useful for different implementations of the same interface. For example, for the design of the database connection pool interface, we can have a variety of interface implementation classes to complete the same function, while users can simply modify the configuration file to specify the actual use of which implementation class, in the source code by reading the configuration file information, and Class.forName ( Configclassname). getinstance () can construct a specific instance of an implementation class without having to modify the source code each time. So for the program to only care about the definition of interface, users only use the configuration file settings to complete the same function of the different implementation of the switch.

But if the implementation class needs to be initialized by a static method, the dynamic loading process can be a bit more complicated. Similarly, in the case of database connection pooling, the constructor of the connection pool is usually defined as private, and a unique instance is obtained by a custom getinstance () static method. In this case, the instance can not be constructed correctly by simply Class.forName (). getinstance ().

Fortunately, the reflection mechanism provided by Java (Reflection) provides us with a complete approach to the internal structure of the class. With the reflection mechanism, we are able to perform essentially all runtime-determined actions (although this implementation is much more complex than the use of eval () in other dynamic languages, such as PHP).

The following practical examples illustrate how to dynamically access a static method of a class at run time.

-------------------------------------------------------
*/
Import java.lang.reflect.*;
Public  Class mytestclass{
private static Object Plock = new Object ();
private static Mytestclass p_instance = null;
Private String S_configname = "";
Private Boolean b_isfromresource = true;    
public static Object getinstance (String sconfigname,
Boolean bisfromresource) {
synchronized (plock) {
   if (null = = p_instance) {
P_instance =new mytestclass (sconfigname,bisfromresource);
 
}
Return p_instance
  
Private Mytestclass (String Sconfigname,boolean bisfromresource) {
S_configname = sconfigname;
B_isfromresource = Bisfromresource.booleanvalue ();
}
public void Echoinfo () {
System.out.println (' current arguments:configname=[' +
s_configname+ '],i sfromresource=["+b_isfromresource+"] ");
}
public static void Main (string[] args) throws exception{
//sets the type of the incoming parameter for the method.
  class[] parametertypes = new class[]{
Java.lang.String.class,
Java.lang.Boolean.class
};
Method mgetinstance = null;
String className = "Mytestclass";
Class curtestclass = Class.forName (className);   
try{
Mgetinstance = Curtestclass.getmethod ("getinstance", parametertypes);
   
catch (Nosuchmethodexception e) {
E.printstacktrace ();
Mgetinstance = null;
}
if (mgetinstance!= null) {
Mytestclass pobj = (mytestclass)
Mgetinstance.invoke (null,new obje    ct[]{
"Src/myconfig.properties",
Boolean.false
}
);
Pobj.echoinfo ();
}
else{
throw
New Exception ("MyTest Init Failed from class" +
ClassName +
Sy Stem.getproperty ("Line.seperator", "\ n") +
Method getinstance (String, Boolean) exists. ");
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.