繁体   English   中英

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

[英]Java: get the class of the inherited class from a static method

我在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();

谢谢你的帮助!

大卫

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

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

好吧, 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);

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和代码分析工具会发出警告,甚至可以自动纠正。

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

Derived.foo();

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

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中强制implement foo

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM