简体   繁体   中英

How can I reflectively get a field on a Scala object from 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 those variables? I can get a method from an object by can't seem to figure out how to get fields. Is this possible?

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

Thanks!

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM