「Java/reflection」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「==reflectionとは== privateのプロパティやメソッドにアクセスする ==reflectionサンプル== 参考:https://qiita.com/ohke/items/b096c5cb9d2932764f22」) |
(→reflectionサンプル) |
||
行3: | 行3: | ||
==reflectionサンプル== | ==reflectionサンプル== | ||
+ | |||
+ | ===通常アクセス=== | ||
+ | <pre> | ||
+ | Animal.java | ||
+ | public class Animal { | ||
+ | public String name = "animal"; | ||
+ | public int foot = 4; | ||
+ | public int getFoot() { | ||
+ | return foot; | ||
+ | } | ||
+ | } | ||
+ | </pre> | ||
+ | main.java | ||
+ | <pre> | ||
+ | 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 | ||
+ | </pre> | ||
+ | |||
+ | ===reflectionでprivateプロパティアクセス=== | ||
+ | Animal.java | ||
+ | <pre> | ||
+ | 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 | ||
+ | </pre> | ||
+ | |||
参考:https://qiita.com/ohke/items/b096c5cb9d2932764f22 | 参考:https://qiita.com/ohke/items/b096c5cb9d2932764f22 |
2019年6月18日 (火) 17:56時点における版
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