| 
 
| 本帖最后由 任我行 于 2015-1-8 10:47 编辑 
 复制代码package com.itheima.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class Test2
{
        /**
         * 编写一个类,增加一个实例方法用于打印一条字符串。并使用反射手段创建该类的对象, 并调用该对象中的方法。##
         */
        
        public static void main(String[] args) throws Exception
        {
                //方式一
                 Class<?> class1 = Class.forName("com.itheima.test.Demo");
                 Constructor<?> con =class1.getConstructor();
                 Demo demo  = (Demo)con.newInstance();
                 Method method = class1.geMethod("show");
                 method.invoke(demo);
                 //方式二
                 Class<?>class2 = Class.forName("com.itheima.test.Demo");
                 Method method1 =class2.getMethod("show");
                 method1.invoke(null);
        } 
}
//实体类
package com.itheima.test;
public  class Demo
{
                public static void  show()
                {
                        System.out.println("反射調用該方法");
                }
}
 
 | 
 |