> 通過反射機制,調用一個對象的方法
# 調用方法
首先為Hero的name屬性,增加setter和getter
通過反射機制調用Hero的setName
實體類:
```
package charactor;
public class Hero2 {
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 Hero2() {
}
public Hero2(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(Hero2 h2) {
System.out.println(this.name + " 正在攻擊 " + h2.getName());
}
}
```
測試類:
```
package com.dodoke.reflection;
import java.lang.reflect.Method;
import charactor.Hero2;
public class TestReflection5 {
public static void main(String[] args) {
Hero2 h = new Hero2();
try {
// 獲取這個名字叫做setName,參數類型是String的方法
Method m = h.getClass().getMethod("setName", String.class);
// 對h對象,調用這個方法
m.invoke(h, "蓋倫");
// 使用傳統的方式,調用getName方法
System.out.println(h.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```