P45 Imminent
P45 Imminent

Reputation: 8591

Correct way of achieving this.class using reflection

Suppose I have a class Foo in package my.package which contains some static fields.

I want to use reflection to get the values of those static fields.

I know I can write my.package.Foo.class.getDeclaredField(... but this is unsatisfactory as I'm hardcoding the class and package names.

I'd like to use this.class.getDeclaredField(... but this is invalid in Java even if called from within a non-static member function.

Is there a way?

Upvotes: 2

Views: 40

Answers (2)

Pokechu22
Pokechu22

Reputation: 5046

Non-statically, you can use this.getClass() to get the current class, as @sotirios-delimanolis mentioned.

Statically, you can do this, though it is a bit ugly:

public static Class<?> getCurrentClassStatic() {
    try {
        return Class.forName(new Throwable().getStackTrace()[0].getClassName());
    } catch (ClassNotFoundException e) {
        return null; //Shouldn't happen...
    }
}

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280132

Every class inherits the instance method Object#getClass(). Invoke that to get your instance's corresponding Class object.

I don't know why you would do this inside Foo as Foo already knows its static fields and you'd have access to them at compile time directly.

Upvotes: 3

Related Questions