facebook twitter hatena line google mixi email

Java/reflection

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

reflectionとは

privateのプロパティやメソッドにアクセスする

proguardが効いてる場合はprivateへアクセスできないので、その場合は、使えないことに注意。

reflectionサンプル

通常アクセス

Animal.java
public class Animal {
    public String name = "animal";
    public int foot = 4;
    public int getFoot() {
        return foot;
    }
}

main.java

Animal animal = new Animal();
Log.i(TAG, "name=" + animal.name); // animal
Log.i(TAG, "foot=" + animal.foot); // 4
Log.i(TAG, "getFoot=" + animal.getFoot()); // 4

reflectionでprivateプロパティアクセス

Animal.java

public class Animal {
    private String name = "animal";
    private int foot = 4;
}

main.java

try {
  Animal animal = new Animal();
  Class animalClass = animal.getClass();
  Field nameField = animalClass.getDeclaredField("name");
  Field footField = animalClass.getDeclaredField("foot");
  nameField.setAccessible(true);
  footField.setAccessible(true);
  Log.i(TAG, "nameField=" + (String)nameField.get(animal)); // animal
  Log.i(TAG, "footField=" + (int)footField.get(animal)); // 4
} catch (NoSuchFieldException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (SecurityException e) {
    e.printStackTrace();
} catch (IllegalArgumentException e) {
    e.printStackTrace();
} catch (NoSuchMethodException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
}

reflectionでprivateのメソッドにアクセス

Animal.java

public class Animal {
    private String name = "animal";
    private int foot = 4;
    private int getFoot() {
        return foot;
    }
}

main.java

try {
  Animal animal = new Animal();
  Class animalClass = animal.getClass();
  Method method = animalClass.getDeclaredMethod("getFoot");
  method.setAccessible(true);
  Log.i(TAG, "getFootField=" +  (int)method.invoke(animal)); // 4
} catch (NoSuchFieldException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (SecurityException e) {
    e.printStackTrace();
} catch (IllegalArgumentException e) {
    e.printStackTrace();
} catch (NoSuchMethodException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
}


参考:https://qiita.com/ohke/items/b096c5cb9d2932764f22