黑马程序员技术交流社区

标题: 反射自定义的Print类,调用其打印字符串的方法 [打印本页]

作者: 老衲玩IT    时间: 2013-8-27 08:35
标题: 反射自定义的Print类,调用其打印字符串的方法
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);
        }
}






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2