How should I return different types in a method based on the value of a string in Java?

Posted by Siracuse on Stack Overflow See other posts from Stack Overflow or by Siracuse
Published on 2010-04-26T16:41:57Z Indexed on 2010/04/26 16:43 UTC
Read the original article Hit count: 217

Filed under:
|

I'm new to Java and I have come to having the following problem:

I have created several classes which all implement the interface "Parser". I have a JavaParser, PythonParser, CParser and finally a TextParser.

I'm trying to write a method so it will take either a File or a String (representing a filename) and return the appropriate parser given the extension of the file.

Here is some psuedo-code of what I'm basically attempting to do:

public Parser getParser(String filename)  
{
    String extension = filename.substring(filename.lastIndexOf("."));

    switch(extension)
    {
        case "py": return new PythonParser();
        case "java": return new JavaParser();
        case "c": return new CParser();
        default: return new TextParser();
    }
}

In general, is this the right way to handle this situation? Also, how should I handle the fact that Java doesn't allow switching on strings? Should I use the .hashcode() value of the strings?

I feel like there is some design pattern or something for handling this but it eludes me. Is this how you would do it?

© Stack Overflow or respective owner

Related posts about java

Related posts about beginner