How can I flip a field in a Scala object with Java?

I have the following object:

 package com.rock

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

How can I use Java reflection to get the values ​​of each of these variables? I can get the method from the object, I can’t figure out how to get the fields. Is it possible?

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

Thank!

+3
source share
3 answers

It 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 displays the result 334322.3

+2
source

clazz.getDeclaredFields() - , , . . getDeclaredMethods. , , . , , .

0

I'm not sure what you are trying to achieve, but if you just want the values ​​not to need reflection:

public class Test {
    public static void main(String[] s) {
        System.out.println(com.rock.Asteriod$.MODULE$.orbitDiam());
    }
}
0
source

All Articles