10

maybe it is trivial question, but is there some way in Java how to get current class reference? Something like this for class, not for object? Eg. in static method I need to refer to current class, how can I get it?:

public class Test {
    public static void test(){
        this.getClass(); // not working, can not use this to return class object Test
    }
}

To more specify my question:

Is something in JAVA like this for current class, or do I have to use ClassName.class, even if I am inside some class, to get this class reference?

Roman C
  • 49,761
  • 33
  • 66
  • 176
kasi
  • 955
  • 1
  • 12
  • 21

2 Answers2

3

static method cannot have this reference, static method is associated with class state.

You can use Test.class.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
jmj
  • 237,923
  • 42
  • 401
  • 438
3

You should use the class literal as follows -

Test.class
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
  • 5
    Yes I know about this format but I don't want to use class name. Just to point to current class. – kasi May 07 '14 at 21:17
  • 1
    Because I was curious if there is any other way to do it, to not need to type different code for different classes. – kasi May 07 '14 at 21:21
  • FAIK, this is the best way. You can use reflection, but you would have provide the fully qualified class name as a string, which is even worse. – Bhesh Gurung May 07 '14 at 21:22
  • OK, so nothing like `this` exists for current class, I have to use `ClassName.class`, even if I am inside some class, to get this class reference. – kasi May 07 '14 at 21:27
  • 1
    That's correct, unless you want to do something like `Class.forName("pkg.Test")`, which is a lot worser than just doing `Test.class`. – Bhesh Gurung May 07 '14 at 21:29
  • 4
    what the op want is the equivalent of ```__PACKAGE__``` in perl. – dwery Dec 01 '15 at 18:00