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();
}
}
}
|
|