Java/reflection
提供: 初心者エンジニアの簡易メモ
reflectionとは
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; } <pre> main.java <pre> 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