Java:从静态方法获取继承类的类

时间:2012-02-01 00:22:07

标签: java inheritance

我在Java中遇到以下问题: 我有一个基类和一个派生类,我在基类中有一个方法。当我通过Derived调用Base的foo方法时,我希望得到Derived的类。如果可以这样做,foo方法可以是通用的。

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

class Derived extends Base
{
}

Derived.foo();

感谢您的帮助!

大卫

5 个答案:

答案 0 :(得分:4)

这不是静态方法的工作方式。您必须实施Derived.foo(),对Derived执行特殊操作,然后该方法调用Base.foo()。如果您确实需要类型信息,可以创建Base.foo0(Class klass)

但说实话,任何需要知道它所调用的类的类型的静态方法应该是一个实例方法。

答案 1 :(得分:3)

好吧,Derived.foo()的来电者知道他们在叫什么,所以你可以改变你的方法:

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);

答案 2 :(得分:1)

static方法不会被继承。具有相同签名的静态方法只能隐藏超类中的类似方法。这意味着你永远不会看到你可能想要的结果 - 你总是完全知道封闭的类。静态方法永远不可能以某种方式“在”另一个类中。所以不可能产生预期的结果。从这个原因调用子类或实例中的静态方法是一个坏主意,因为它只是隐藏了真正的类。 (IDE和静态代码分析工具可以标记或更正此。)

来源:

那么使用继承方法的方法不适用于未继承的static方法。

class Base {
    static void foo() {
        // Only the static context is available here so you can't get class dynamic class information
    }
    void bar() {
        System.out.println(getClass());
    }
}
class Derived extends Base {
}
class Another extends Base {
    static void foo() {
         // No super call possible!
         // This method hides the static method in the super class, it does not override it.
    }
    void bar() {
         super.bar();
    }
}

Derived derived = new Derived();
derived.bar(); // "class Derived"
Base base = new Base();
base.bar(); // "class Base"

// These are only "shortcuts" for Base.foo() that all work...
derived.foo(); // non-static context
Derived.foo(); // could be hidden by a method with same signature in Derived 
base.foo(); // non-static context

Base.foo(); // Correct way to call the method

Another a = new Another();
a.foo(); // non-static context
Another.foo(); 

语言是否允许这样做是否好主意? - 嗯。我认为这说明IDE和代码分析工具会发出警告,甚至可以自动纠正。

答案 3 :(得分:0)

不可能,Derived.foo()只会为Base.foo()提供代码。

答案 4 :(得分:-1)

Derived.foo();

转到foo中定义的Derived,如果在那里定义的话:

class Base {
    static void foo() {
    System.out.println("Base");
    }
}

class Der extends Base {
    static void foo() {
    System.out.println("Der");
    }
}

class Check {
    public static void main(String[] args) {
    Base.foo();
    Der.foo();
    }
}

当我运行它时:

javac -g Check.java && java Check 
Base 
Der

那你的问题是什么?如果要求每个派生类implement foo都不可能在Java中强制执行。

相关问题