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");
}}
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");
}}
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,所以有黄线的!给调用的方法穿参数就好了!
Method methodShow = testClass.getMethod("show");
// invoke对带有指定参数的指定对象调用由此 Method 对象表示的底层方法
Object obj = methodShow.invoke(ts);
com.itheima.TestString的show方法
invoke的返回值如果你后面用不上Object obj 自然可以去掉,留在那也没什么影响