Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: get the class of the inherited class from a static method

I have the following problem in Java: I have a base class and a derived class and I have a method in the base class. When I call the Base's foo method through Derived I want to get the Derived's class. The foo method can be generic if it can be done that way.

class Base
{
    static void foo()
    {
        // I want to get Derived class here
        // Derived.class
    }
}

class Derived extends Base
{
}

Derived.foo();

Thanks for your help!

David

like image 968
seriakillaz Avatar asked Feb 01 '12 00:02

seriakillaz


People also ask

Are static methods inherited to derive class?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor.

Does static method gets inherited in Java?

Static methods take all the data from parameters and compute something from those parameters, with no reference to variables. We can inherit static methods in Java.

Can a customer be inherited by a derived class from the base class?

It is also known as parent class or superclass. It is also known as child class subclass. 3. It cannot inherit properties and methods of Derived Class.

Why we Cannot override static method?

Overloading is the mechanism of binding the method call with the method body dynamically based on the parameters passed to the method call. Static methods are bonded at compile time using static binding. Therefore, we cannot override static methods in Java.


2 Answers

That's not the way that static methods work. You'll have to implement Derived.foo(), do whatever it is that's special to Derived, and that method then calls Base.foo(). If you really need the type information, you could create Base.foo0(Class klass).

But to be honest, any static method that needs to know that type of the class that it's invoked on should probably be an instance method.

like image 136
parsifal Avatar answered Oct 21 '22 08:10

parsifal


Well, the caller of Derived.foo() knows what they are calling, so you could alter your methods thus:

class Base
{
    static void foo(Class< T > calledBy)
    {
        // I want to get Derived class here
        // Derived.class
    }
}

class Derived extends Base
{
}

Derived.foo(Derived.class);
like image 31
Raedwald Avatar answered Oct 21 '22 09:10

Raedwald