- package com.test;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Method;
- public class DemoTest2
- {
- public DemoTest2(String s1, String s2)
- {
- System.out.println(s1);
- System.out.println(s2);
- }
- public void output(String str)
- {
- System.out.println("hello: " + str);
- }
- @SuppressWarnings("unchecked")
- public static void main(String[] args)throws Exception
- {
- // 1. 得到该对象所对应的Class对象
- Class<DemoTest2> clazz = DemoTest2.class;
- //2. 通过该Class对象得到该类的构造方法所对应的Constructor对象
- Constructor cons = clazz.getConstructor(new Class[]{String.class, String.class});
- //3. 通过该Constructor对象的newInstance方法得到该类的一个实例(对象)
- DemoTest2 test = (DemoTest2)cons.newInstance(new Object[]{"abc","xyz"});
- //4. 通过该Class对象得到该方法所对应的Method对象
- Method method = clazz.getMethod("output",new Class[]{String.class});
- //5. 通过该Method对象的invoke方法进行调用
- method.invoke(test,new Object[]{"zhangsan"});
- //new DemoTest2().output("zhangsan");
- }
- }
转载于:https://blog.51cto.com/huqianhao/955186