反射机制 调用方法
通过反射机制,调用一个对象的方法
步骤 1 : 调用方法
首先为Hero的name属性,增加setter和getter
通过反射机制调用Hero的setName
package charactor;
public class Hero {
public String name;
public float hp;
public int damage;
public int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Hero(){
}
public Hero(String string) {
name =string;
}
@Override
public String toString() {
return "Hero [name=" + name + "]";
}
public boolean isDead() {
// TODO Auto-generated method stub
return false;
}
public void attackHero(Hero h2) {
// TODO Auto-generated method stub
}
}
.
package reflection;
import java.lang.reflect.Method;
import charactor.Hero;
public class TestReflection {
public static void main(String[] args) {
Hero h = new Hero();
try {
// 获取这个名字叫做setName,参数类型是String的方法
Method m = h.getClass().getMethod("setName", String.class);
// 对h对象,调用这个方法
m.invoke(h, "盖伦");
// 使用传统的方式,调用getName方法
System.out.println(h.getName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
练习: 调用方法