JAvaプレミアム36-反射呼び出し方法

2478 ワード

1.呼び出し方法
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();
        }
 
    }
}

2.プロファイルからオブジェクトを取得
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
 
import charactor.Hero;
 
public class TestReflection {
    public static void main(String[] args) throws InterruptedException {
        File f = new File("E:/project/j2se/hero.config");
 
        try (FileReader fr = new FileReader(f)) {
            String fileContent = null;
            char[] all = new char[(int) f.length()];
            fr.read(all);
            fileContent = new String(all);
            String[] cs = fileContent.split("\r
"); String hero1className = cs[0]; String hero1Name = cs[1]; String hero2className = cs[2]; String hero2Name = cs[3]; // , hero1, hero1 name Class hero1Class = Class.forName(hero1className); Constructor hero1Constructor = hero1Class.getConstructor(); Object hero1 = hero1Constructor.newInstance(); Field hero1NameField = hero1Class.getField("name"); hero1NameField.set(hero1, hero1Name); // , hero2, hero2 name Class hero2Class = Class.forName(hero2className); Constructor hero2Constructor = hero2Class.getConstructor(); Object hero2 = hero2Constructor.newInstance(); Field hero2NameField = hero2Class.getField("name"); hero2NameField.set(hero2, hero2Name); // , attackHero , hero1 , hero2 Method attackHeroMethod = hero1Class.getMethod("attackHero", Hero.class); attackHeroMethod.invoke(hero1, hero2); } catch (Exception e) { e.printStackTrace(); } } }