0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

オブジェクト(Generics・総称型)を使用して未知のクラスのメンバ変数を列挙する

Posted at

Generics・総称型を使用して未知のクラスのメンバ変数名とメンバ変数の中身を列挙します

public class Hoge {
    public static void report(Object input_row) throws IllegalArgumentException, IllegalAccessException {
    	for(Field field: input_row.getClass().getFields()) {// publicメンバだけ
        //for(Field field: input_row.getClass().getDeclaredFields()) { // 全てのメンバ
    		//field.setAccessible(true); // これが必要な場合もあるらしい
    		System.out.println("###: " + field.getName() + " : " + field.get(input_row));
    	}
    }
}

field.setAccessible(true); について

こちらのサイトより
https://www.glamenv-septzen.net/view/449#id45308a

Test5.javaでIllegalAccessExceptionが発生したのは、Java言語のアクセス制御チェックがprivateなのでアクセス不可能と判定>したからである。
java.lang.reflectパッケージには Field の他に Constructor, Method というクラスが用意されているが、これらは java.lang.reflect.AccessibleObject というクラスを基底クラスとしている。
そして AccessibleObject クラスには、対象Field/Constructor/Methodに対するアクセス制御チェックの有効/無効を設定する setAccessible(boolean) というメソッドがある。
setAccessible(true)とすることで、アクセス制御チェックを抑制し、privateなメンバも外部からアクセスできるようになる。

とのことで field.get でExceptionが起きるパターンもあるので覚えておいたほうが良いと思います

作成中やらかしたミス

Exception の handle をしなかったためビルドが通らなかった

public static void report(Object input_row) throws IllegalArgumentException, IllegalAccessException {

こうすべき箇所を

public static void report(Object input_row) {

こう書いていたのでビルドが通らず結構な時間悩んでました
Javaの基本なのでなにやってんだという感じではあります
unhandled ~~ Exception とメッセージが出ていたのでちゃんとメッセージ読もうねという話でした

以上です

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?