Recently in the network programming to do a small server, in mapping this piece encountered a small problem: how to jump to the corresponding class after the handler, that is, how to create an instance based on the class name.
Here are two forms: with parameters and without parameters, the following is my understanding, whether completely correct to be verified:
1. For the case without parameters, first get the class object, and then call the Newinstance method can get an example of the empty argument list, namely:
Class C = class.forname (className);//Note the fully qualified name, that is, the package name, etc.
C.newinstance ();
2. To create an instance with a parameter, you need to obtain a constructor after you get the class object for that type, such as Class.getconstructor (Class...parametertypes), such as Class.getconstructor ( String.class,outputstream.class), which represents a constructor method with a parameter list type (String,outputstream), and the return value is Java.lang.reflect.Constructor. There are methods Newinstance (object...parameters) in this class, that is, to pass parameters to this constructor, get the corresponding instance, the following is an example of creating a class Indexhandler instance in the handler package. One of the constructor methods in the Indexhandler class is public Indexhandler (OutputStream outputstream,string request):
Class C = Class.forName ("handler." +handler);
Java.lang.reflect.Constructor constructor = C.getconstructor (Outputstream.class,string.class);//Order not variable
Constructor.newinstance (OUTPUTSTREAM,STR);
Because the return value is generic, you cannot directly invoke the method in the class without knowing the class name, such as Constructor.newinstance (OUTPUTSTREAM,STR) in the example above. function (), to invoke a method in a class, You can use the Class.getmethod or GetMethods method, whose return value type is methods and the class in Java.lang.reflect, and then Invoke method invoke, as follows:
class<?> C = class.forname (ClassName);
Constructor<?> constructor = C.getconstructor (String.class); Suppose the class has a constructor classname (String name)
Object o = constructor.newinstance ("Zhengjunyan"); Equivalent to New ClassName ("Zhengjunyan")
Method method = C.getmethod ("Test", String.class); Suppose there is a method test (String s) in the class
Method.invoke (O, "Zheng"); The method Test ("Zheng") that invokes the instance that has been created