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

© 刘德坤 中级黑马   /  2015-10-8 22:56  /  181 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package com.itheima;

import java.lang.reflect.Method;


/*
* 6、编写一个类,增加一个实例方法用于打印一条字符串。
* 并使用反射手段创建该类的对象, 并调用该对象中的方法。
* */
//对象的打印方法
class Println{
        public void println(String str){
                System.out.println(str);
        }
}
public class Test19 {
        public static void main(String[] args) throws Exception {
                Class<?> clazz = Class.forName("com.itheima.Println");//通过反射的方式获取该类的字节码文件
                Method method = clazz.getMethod("println",String.class);//获取字节码对象对应的方法,并指定参数类型。
                method.invoke(clazz.newInstance(),"黑马程序员训练营我来了");//运行对象中的方法,并传入参数。
        }
}

0 个回复

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