package com.itheima;
import java.lang.reflect.*;/*
 * 5、 编写一个类,增加一个实例方法用于打印一条字符串。并使用反射手段创建该类的对象, 并调用该对象中的方法。
 * */public class Test5 {
public static void main(String[] args) throws Exception {
//为了代码的可读性 这里就抛出异常了
Class<?> testClass = Class.forName("com.itheima.TestString");
TestString ts = (TestString)testClass.newInstance();
// 通过反射获得TestString类的字节码
Method methodShow = testClass.getMethod("show", null);
// invoke对带有指定参数的指定对象调用由此 Method 对象表示的底层方法
     Object obj = methodShow.invoke(ts, null);
}
}class TestString {
public static void show() {
System.out.println("hello heima");
}}

解决方案 »

  1.   


    public class Test5 {
    public static void main(String[] args) throws Exception {
    // 为了代码的可读性 这里就抛出异常了
    Class<?> testClass = Class.forName("com.itheima.TestString");
    com.itheima.TestString ts = (com.itheima.TestString) testClass.newInstance();
    // 通过反射获得TestString类的字节码
    Method methodShow = testClass.getMethod("show", Integer.class);
    // invoke对带有指定参数的指定对象调用由此 Method 对象表示的底层方法
    Object obj = methodShow.invoke(ts, Integer.valueOf(1));
    }
    }class TestString {
    public static void show() {
    System.out.println("hello heima");
    }}这样把!以为你传的null,所以有黄线的!给调用的方法穿参数就好了!
      

  2.   


    Method methodShow = testClass.getMethod("show");
    // invoke对带有指定参数的指定对象调用由此 Method 对象表示的底层方法
    Object obj = methodShow.invoke(ts);
      

  3.   

    你给你的show方法加一个Integer的参数,看他还报错不了!
    com.itheima.TestString的show方法
      

  4.   

    我像上面那位这样去掉null 也去掉Object obj 这样可以吗?
      

  5.   

    getMethod ,invoke你查一下API文档就知道它第2个参数实际是个可变长度参数,没有自然可以不写,写个null也没什么错
    invoke的返回值如果你后面用不上Object obj 自然可以去掉,留在那也没什么影响