示例代码:
- import java.lang.reflect.Constructor;
- public class TestConstructor {
-
-
-
-
-
-
- public static void main(String[] args) throws Exception {
-
- Class classType=Class.forName(args[0]);
- Constructor Constructor= classType.getConstructor();
-
- System.out.println(Constructor.toString());
-
- }
- }
|
5)新建类的实例
调用类的Class对象的newInstance方法
- import java.lang.reflect.Constructor;
-
-
- public class TestConstructor {
-
-
-
-
-
-
- public static void main(String[] args) throws Exception {
-
- Class classType=Class.forName(args[0]);
-
- Object inst=classType.newInstance();
- System.out.println(inst);
- }
- }
|
调用默认Constructor对象的newInstance方法
- import java.lang.reflect.Constructor;
-
-
- public class TestConstructor {
-
-
-
-
-
-
- public static void main(String[] args) throws Exception {
-
- Class classType=Class.forName(args[0]);
- Constructor Constructor= classType.getConstructor();
- Object inst=Constructor.newInstance();
- System.out.println(inst);
- }
- }
|
调用带参数Constructor对象的newInstance方法
- Class classType=User.class
- Constructor constructor2 =
- classType.getDeclaredConstructor(int.class, String.class);
-
- Object inst = constructor2.newInstance(1, "123");
-
- System.out.println(inst);
|
相关链接:
Java反射机制剖析:定义和API