簡體   English   中英

如何基於Java中的if語句在實用程序類中創建對象? (或基於特定字符串)

[英]How to create an object in a utility class based on if statement in Java? (Or based on a particular string)

我將有一個解析成數組的字符串,如下所示:

class Example extends ParentClass {
    private String[] array;

    public static Example parseString(String lineToParse) {
        array = lineToParse.split("\");
    }

    public ObjectType1() { // arguments: String, String, String
    }

    public ObjectType2() { // arguments: String, String, String, double, double
    }
}

我想知道的是我可以這樣做嗎?

if (array[0].equals("Test")) {
     public ObjectType1()
}

或者有更好的方法嗎?

我想創建各自具有不同參數的各種對象,第一個參數( array[0] )將適用於每個對象,所以我想知道是否可以在if語句中創建對象,或者switch (不確定)如果那樣也可以)。

我相信一個工廠方法對你有用,一個根據收到的參數返回類的實例:

// ObjectType1, ObjectType2, ObjectType3 inherit from ObjectType
static ObjectType getInstance(String[] array) {
    if (array[0].equals("Test"))
        return new ObjectType1(array);
    else if (array[0].equals("Test2"))
        return new ObjectType2(array);
    else
        return new ObjectType3(array);
}

對於記錄,實際上你可以在方法中定義一個類,這是Java中的有效代碼......當然,這不是一件好事:

// ObjectType1, ObjectType2 inherit from ObjectType
public ObjectType example(String[] array) {
    if (array[0].equals("Test")) {
        class ObjectType1 {
            ObjectType1(String[] array) {
            }
        }
        return new ObjectType1(array);
    }
    else {
        class ObjectType2 {
            ObjectType2(String[] array) {
            }
        }
        return new ObjectType2(array);
    }
}

“創建”對象意味着“實例化”,使用new:

ObjectType1 foo = new ObjectType1(...);

您可以在實例化類的合法地方執行此操作,包括在if語句中。

但是,您無法在任意位置定義類。

如果您只想調用一個方法(如果您希望Java開發人員了解您嘗試做什么,則應該以小寫字母開頭),您可以從任何地方調用它,包括if語句內部。

這聽起來像你可能想要使用[靜態工廠方法] [1]。

[1]: http://en.m.wikipedia.org/wiki/Factory_method_pattern

我想你想根據配置文件動態創建對象?

有很多方法可以實現這一目標。 一種簡單的方法是使用反射來創建對象。 然后,您不需要任何if / switch語句,如果要創建新類型的對象,則不需要更改代碼。

以下是使用反射的一些示例: Reflection API代碼示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM