ReflectExercise1
package ReflectExercise20240821;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectExercise1 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//1.获取字节码文件对象
Class clazz = Class.forName("ReflectExercise1.Student");
//2.获取一个对象
//需要用这个对象去调用方法
Student s = new Student();
//3.获取一个指定的方法
//参数一:方法名
//参数二:参数列表,如果没有可以不写
Method eatMethod = clazz.getMethod("eat",String.class);
//运行
//参数一:表示方法的调用对象
//参数二:方法在运行时需要的实际参数
//注意点:如果方法有返回值,那么需要接收invoke的结果
//如果方法没有返回值,则不需要接收
String result = (String) eatMethod.invoke(s, "重庆小面");
System.out.println(result);
}
}
Student
package ReflectExercise20240821;
import java.util.Objects;
public class Student {
private String name;
private int age;
public String gender;
public String address;
public Student() {
}
public Student(String name) {
this.name = name;
}
private Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Student{name = " + name + ", age = " + age + "}";
}
private void study(){
System.out.println("学生在学习");
}
private void sleep(){
System.out.println("学生在睡觉");
}
public String eat(String something){
System.out.println("学生在吃" + something);
return "学生已经吃完了,非常happy";
}
}