「Java/reflection」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→reflectionサンプル) |
(→reflectionでprivateプロパティアクセス) |
||
行30: | 行30: | ||
private int foot = 4; | private int foot = 4; | ||
} | } | ||
− | <pre> | + | </pre> |
main.java | main.java | ||
<pre> | <pre> | ||
行41: | 行41: | ||
Log.i(TAG, "nameField=" + (String)nameField.get(animal)); // animal | Log.i(TAG, "nameField=" + (String)nameField.get(animal)); // animal | ||
Log.i(TAG, "footField=" + (int)footField.get(animal)); // 4 | Log.i(TAG, "footField=" + (int)footField.get(animal)); // 4 | ||
+ | </pre> | ||
+ | |||
+ | |||
+ | Animal.java | ||
+ | <pre> | ||
+ | public class Animal { | ||
+ | private String name = "animal"; | ||
+ | private int foot = 4; | ||
+ | private int getFoot() { | ||
+ | return foot; | ||
+ | } | ||
+ | } | ||
+ | </pre> | ||
+ | main.java | ||
+ | <pre> | ||
+ | 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 | ||
</pre> | </pre> | ||
参考:https://qiita.com/ohke/items/b096c5cb9d2932764f22 | 参考:https://qiita.com/ohke/items/b096c5cb9d2932764f22 |
2019年6月18日 (火) 18:00時点における版
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; }
main.java
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
Animal.java
public class Animal { private String name = "animal"; private int foot = 4; private int getFoot() { return foot; } }
main.java
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