java - 从方法返回值而不创建对象

标签 java class methods

好吧,我有一个大的类结构,看起来像 THIS

它适合学校使用,我的导师喜欢星际争霸,所以我们就开始吧。

无论如何,我在GeneratorBuilding 类中有一个方法应该能够实例化一个新的Marine 对象。但是,我需要知道一个Marine 对象需要多少资源。

我在抽象 Unit 类中有一个抽象 int 方法,称为 unitCost()。然后 Marine 类重写此方法并返回一个值,例如 50。

我正在寻找一种方法,让我的 GeneratorBuilding 类获得 Marine 类中 unitCost() 方法的返回值,而无需调用任何特定的 Marine 对象。

我知道我可能会创建一个海洋对象,然后询问它的成本是多少,然后如果我没有资源,我会删除该对象而不是将其插入 ArrayList。但这似乎几乎是一种解决方法。

编辑:重点是能够让我所有的具体类继承并覆盖 UnitCost() 方法。所以我可以使它成为静态的,但这破坏了继承结构的全部意义......

EDIT2:因为有示例代码的请求(不难想象)

public void makeMarine(){

    //uses resources and throws exception etc if there are not enough resources
    Game.useResources(Marine.unitCost());

    //creates a marine
    Game.addMarine();
}

最佳答案

您可以通过在每个类中声明一个专门命名的静态字段,并通过反射}获取它来做到这一点。

假设您的类如下所示:

class ClassNumber1 {
    public static final int cost = 123;
}
class ClassNumber2 {
    public static final int cost = 321;
}

然后你可以像这样获取他们的cost字段:

public static <T> int getCost(Class<T> cl) throws Exception {
    // This is oversimplified: you need to check that the class
    // indeed has a field called "cost" by null-checking the return value
    // of getField(), verifying your cast, catching exceptions, and so on.
    // But this will work in a "closed" system, when you know for sure
    // that an int constant field does exist:
    return (int)cl.getField("cost").get(null);
}

按如下方式调用该方法:

System.out.println(getCost(ClassNumber1.class));
System.out.println(getCost(ClassNumber2.class));

这是一个demo on ideone .

关于java - 从方法返回值而不创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16095837/

相关文章:

java - Java中如何在当前类中引用不同类的实例

c# - Dynamics AX 动态调用非静态方法

java - 如何登录我的新 Spring Boot 应用程序?

java - 安卓网络

java - (TensorflowLite/Android) 无法实例化 Activity ComponentInfo

使用公共(public)和私有(private)重载构造函数时的 C++ 垃圾成员值

ios - 如何在 iOS 中调用和声明对象以进行方法调用

c# - 在 C# 中使用字符串调用方法时出现 "Object does not match target type"

java - guice绑定(bind)到实例和asEagersingleton有什么区别

java - java中的字符串匹配操作