Mike
Mike

Reputation: 60743

Java, Get Class object for containing class, Not Runtime Class

Consider this Java code

class A{
 //@returns Class object this method is contained in
 // should be A in this case
 public Class<?> f() {
   return getClass();
 }
}

class B extends A {}

B b = new B();

System.out.println(b.f());
//output -- B.class (Wrong, should be A.class)

inside f() i can't use getClass() because that will give me the runtype, which is B. I'm looking for a way to get the Class object of the class f() is inside (Without mentioning A explicitly, obviously)

Upvotes: 2

Views: 2725

Answers (5)

Duncan McGregor
Duncan McGregor

Reputation: 18157

I know you said you didn't want to mention A.class explicitly

class A {        
    public Class<?> f() {
        return A.class;
    }   
}

but I'm struggling to find a use case where the above code isn't satisfactory.

Upvotes: 1

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147124

new Object() {}.getClass().getEnclosingClass(). But please don't!

Upvotes: 6

Robin
Robin

Reputation: 24262

I would have to say it would be much simpler and more clear to simply return A.class as @mmyers suggested. There is not much point in trying to derive it at runtime if you don't actually want the runtime value. The only issue that comes up is if you refactor the name of the class and another with the same name happens to exist, in the same package.

I would take that chance for the sake of clarity in the code now.

Upvotes: 2

ChssPly76
ChssPly76

Reputation: 100686

You can use exception stack trace facility to do something like this:

public String f() {
    Exception E = new Exception();
    E.fillInStackTrace();
    return E.getStackTrace()[0].getClassName(); // load it if you need to return class
}

Upvotes: 4

sleske
sleske

Reputation: 83577

You can use

class.getMethod("f",parameterTypes).getDeclaringClass()

Upvotes: 1

Related Questions