John
John

Reputation: 123

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!

Upvotes: 3

Views: 753

Answers (3)

thoredge
thoredge

Reputation: 12601

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());
    }
}

Upvotes: 0

dhg
dhg

Reputation: 52681

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

Upvotes: 2

Marko Topolnik
Marko Topolnik

Reputation: 200148

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.

Upvotes: 0

Related Questions