Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

I would have a string that is parsed into an array, as shown here:

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
    }
}

What I'm wondering is could I do this?

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

Or is there a better way to do this?

I want to create various objects with different arguments each, and the first argument (array[0]) will be applicable to each object, so I was wondering if I could create objects within an if statement like this, or a switch (not sure if that would work either).


1 Answers

I believe a factory method would be useful for you, one that returns instances of classes according to the parameter received:

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

For the record, actually you can define a class inside a method, this is valid code in Java ... of course, that's hardly a good thing to do:

// 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);
    }
}
like image 184
Óscar López Avatar answered Dec 09 '25 02:12

Óscar López