A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

package com.itheima;

import java.lang.reflect.Method;

/**
*  编写一个类,增加一个实例方法用于打印一条字符串。并使用反射手段创建
* 该类的对象, 并调用该对象中的方法。
* @author Administrator
*
*/
public class Test {

        public static void main(String[] args) {
                try {
                        Class clazz=Class.forName("com.itheima.Print");
                        //调用Print类的方法
                        Method method=clazz.getDeclaredMethod("printString", String.class);
                        method.invoke(clazz.newInstance(), "编写一个类,增加一个实例方法用于打印一条字符串。并使用反射手段创建该类的对象, 并调用该对象中的方法。");
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }

}
class Print{
        Print(){}
        public void printString(String str) {
                System.out.println(str);
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马