Reputation: 1
Consider this code:
class A {
static int i=3;
}
public class TT extends A {
public static void main(String[] args) {
System.out.println(new A().getClass().i);
}
}
Can the getClass()
method be used to access static variables in this context?
Upvotes: 0
Views: 612
Reputation: 2135
Perhaps this code answers your question:
package com.cc.test;
import java.lang.reflect.Field;
public class TestMain {
public static void main(String[] args) throws Exception {
Class theClass = Class.forName("com.cc.test.TestMain$MyClass");
Field theField = theClass.getField("myField");
int theValue = theField.getInt(null); // null only works if myField is static
System.out.println(theValue); // prints 99
}
private static class MyClass {
public static int myField = 99;
}
}
Upvotes: 1
Reputation: 1502606
Not like that, no. getClass()
returns a Class<?>
, and i
isn't a member of Class
. You could use getClass()
followed by reflection to get the field value, but it's not at all clear what you're trying to achieve here - when in the example you've given (which is all we've got to go by) simply using A.i
would be simpler and clearer.
Upvotes: 9