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

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

package com.itheima;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/*
  题目:编写一个类,增加一个实例方法用于打印一条字符串。并使用反射手段创建该类的对象, 并调用该对象中的方法
  分析:
   1.加载类 Sample
   2.加载无参构造方法  
   3.创建Sample对象  
   4.获得自定义的实例方法
   5.调用自定义的实例方法   
  
  步骤:
   1.Class clazz = Class.forName("com.itheima.Sample");
   2.Constructor constructor = clazz.getConstructor(null);
   3.Sample s = (Sample) constructor.newInstance(null);
   4.Method method = clazz.getMethod("say", null);
   5.method.invoke(s, null);
  
*/
public class Test14 {
         public static void main(String[] args){  
                try {  
                    //加载类  
                    Class clazz = Class.forName("com.itheima.Sample");  
                    //加载无参构造方法  
                    Constructor constructor = clazz.getConstructor(null);  
                    //创建Sample对象  
                    Sample s = (Sample) constructor.newInstance(null);  
                    //获得自定义的实例方法  
                    Method method = clazz.getMethod("getinfo", null);  
                    //调用该方法  
                    method.invoke(s, null);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }   
            }
}

0 个回复

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