3

次のオブジェクトがあります。

 package com.rock

 object Asteriod {
    val orbitDiam = 334322.3
    val radius = 3132.3
    val length = 323332.3
    val elliptical = false
 }

Java リフレクションを使用して、これらの各変数の値を取得するにはどうすればよいですか? フィールドを取得する方法がわかりませんが、オブジェクトからメソッドを取得できます。これは可能ですか?

  Class<?> clazz = Class.forName("com.rock.Asteriod$");
  Field field = clazz.getField("MODULE$");
   // not sure what to do to get each of the variables?????

ありがとう!

4

3 に答える 3

2

This works:

Class<?> clazz = Class.forName("com.rock.Asteriod$");
Object asteroid = clazz.getField("MODULE$").get(null);

Field orbitDiamField = clazz.getDeclaredField("orbitDiam");
orbitDiamField.setAccessible(true);
double orbitDiam = orbitDiamField.getDouble(asteroid);

System.out.println(orbitDiam);

And prints the result 334322.3

于 2012-04-17T22:06:29.437 に答える
0

何を達成しようとしているのかはわかりませんが、値が必要なだけであれば、リフレクションは必要ありません:

public class Test {
    public static void main(String[] s) {
        System.out.println(com.rock.Asteriod$.MODULE$.orbitDiam());
    }
}
于 2012-04-17T22:26:32.077 に答える
0

Start off with clazz.getDeclaredFields() -- this gives you all the fields declared in the class, as opposed to just the public ones. You may well find them to be private and to actually have synthesized getters. So do check all the methods as well with getDeclaredMethods. Print out everything to see what's going on. And if it isn't too much trouble, post back with findings, it could be an interesting read for others.

于 2012-04-17T21:43:18.320 に答える