如何将类传递给方法并在该类上调用静态方法

时间:2019-12-25 00:42:16

标签: java java-8

我正在尝试编写一个工厂类,该类接受从特定抽象基类继承的类,并在基于该类创建一个或多个该类实例之前,对该类调用静态方法以执行一些逻辑和数据操作。操纵数据。到目前为止,这就是我所拥有的:

public abstract class Foobar {
    public static void sayHi() {}
}

public class Foo extends Foobar {
    public static void sayHi() {
        System.out.println("Hi from Foo!");
    }
}

public class Bar extends Foobar {
    public static void sayHi() {
        System.out.println("Hi from Bar!");
    }
}

public class PolymorphicFoobar {
    public PolymorphicFoobar(Class<Foobar> cls) {
        // Do some logic before creating an instance
        cls.sayHi();
    }
}

class Playground {
    public static void main(String[ ] args) {
        // Neither works
        new PolymorphicFoobar(Foo.class);
        new PolymorphicFoobar((Class<Foobar>)Bar.class);
    }
}

1 个答案:

答案 0 :(得分:3)

可以使用 reflection 和捕获的通配符来完成此操作;喜欢

<!DOCTYPE HTML>
<html>
	<head>
		 <meta charset="utf-8" />
		<title>basic game</title>	
	</head>
	
	<body>
	<canvas id="myCanvas" height="500px" width="500px"></canvas>
</body>
</html>

然后调用它,其语法与您所拥有的语法非常相似(您缺少public PolymorphicFoobar(Class<? extends Foobar> cls) { try { Method sayHi = cls.getMethod("sayHi"); sayHi.invoke(cls); } catch (Exception e) { e.printStackTrace(); } } ,但第一种形式很好)。喜欢,

new

输出

public static void main(String[] args) {
    new PolymorphicFoobar(Foo.class);
    new PolymorphicFoobar(Bar.class);
}