java175-method类反射机制
作者:互联网
//class反射编程
//定义一个学生类
public class test124 {
public String name;
protected int age;
double height;
private double money;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public test124(String name, Integer age){
this.name=name;
this.age=age;
System.out.println( "调用有参构造方法" );
}
public test124(String name,int age,double money){
this.name=name;
this.age=age;
this.money=money;
}
//看书
public void learn(BookRead book){
System.out.println( "我的名字"+name+ "我正在学习"+book.getName());
}
//奔跑
public void run(){
System.out.println( "我们喜欢奔跑" );
}
}
定义一个method类
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
//method类反射机制
public class test129 {
public static void main(String[] args){
try {
Class<?> stuCla = Class.forName( "test124" );
test124 stuObj=new test124( "geyao",12 );
BookRead book=new BookRead();
book.setName( "歌谣" );
Method learnMet=stuCla.getMethod( "learn", BookRead.class);
learnMet.invoke( stuObj,book );
//获取非公共方法
Method runMet=stuCla.getDeclaredMethod( "run");
if(!runMet.isAccessible()){
runMet.setAccessible( true );
runMet.invoke( stuObj );
}
}catch (Exception e){
e.printStackTrace();
}
}
}
定义一个bookread类
public class BookRead {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
运行结果
标签:反射,test124,name,age,method,void,public,java175,String 来源: https://www.cnblogs.com/yao-655442/p/16448216.html