使用字符串实例化 class

Using a string to instantiate a class

假设我有 类 圆形、矩形和三角形。

基于数据文件的输入,我想创建适当的对象。例如,如果 shapes.dat 的第一行是 C.5 0 0,我将创建一个半径为 5 的 Circle 对象。如果下一行是 R.5 3 0,我将创建一个长度为 5 的 Rectangle 对象和宽度 3.

我知道我可以使用基本的 if-else 逻辑,但我想知道是否有办法使用字符串作为实例化新对象的方法。有点像 Python 中的 exec() 方法。这是描述我想要的代码片段:

    Scanner file = new Scanner (new File("shapes.dat"));
    String s;       

    Map<Character,String> dict = new HashMap<Character,String>();
    dict.put('C', "Circle");
    dict.put('R', "Rectangle");
    dict.put('T', "Triangle");

    while (file.hasNextLine())
    {
        s = file.nextLine().trim();

        String name = dict.get(s.toCharArray()[0]);
        String data = s.split(".")[1];
        String code = name + " x = new " + name + "(data);";

        SYS.exec(code); //???

        ...

    }

您可以利用反射动态创建实例。

String className = "com.shape.Triangle";
Class classDefinition = Class.forName(className);
Object obj = classDefinition.newInstance();

只需使用 if-else 创建特定 class 的实例。

Exec in Python 执行代码。
你可以用 Java 做同样的事情,例如 javassist.
您可以读取数据文件,编译语句并将它们插入您自己的 class.
但这似乎有点过分了。

您也可以使用 java 反射,但它会产生脆弱且不清晰的代码。

相反 if else if, 我认为您应该使用抽象并按对象类型创建工厂 class。

它可能看起来像:

Scanner file = new Scanner (new File("shapes.dat"));
String s;       

Map<Character, ShapeBuilder> dict = new HashMap<Character,String>();
dict.put('C', new CircleBuilder());
dict.put('R', new RectangleBuilder());
dict.put('T', new TriangleBuilder());

while (file.hasNextLine()){
    s = file.nextLine().trim();
    char shapeSymbol = ...; // computed from s
    ShapeBuilder builder = dict.get(shapeSymbol);
    Shape shape = builder.build(s);
}

我不确定我是否理解正确,似乎很奇怪还没有其他人提到这个:

Map<Character, ShapeFactory> dict = new HashMap<>();
dict.put('C', new CircleFactory());
dict.put('R', new RectangleFactory());
dict.put('T', new TriangleFactory());

...

ShapeFactory factory = dict.get(symbol);
Shape shape = factory.create(data);

您实际上可以使用多态性来避免 if-else 语句。因此,您可以创建实际完成您想要的这两项工作的对象,匹配一条线并创建一个形状。所以你可以使用类似下面的代码。

public class Program {

    public static void main() throws FileNotFoundException {
        Scanner file = new Scanner(new File("shapes.dat"));

        while (file.hasNextLine()) {
            String line = file.nextLine().trim();
            Shape shape = new Matches(
                new RectangleMatch(),
                new TriangleMatch(),
                new SquareMatch(),
                new CircleMatch()
            ).map(line);
        }
    }


    public interface ShapeMatch {
        boolean matches(String line);

        Shape shape(String line);
    }


    public static final class RectangleMatch implements ShapeMatch {
        @Override
        public boolean matches(String line) {
            return line.startsWith("R");
        }

        @Override
        public Shape shape(String line) {
            String[] dimensions = line.substring(2).split(" ");
            return new Rectangle(
                Integer.parseInt(dimensions[0]),
                Integer.parseInt(dimensions[1]),
                Integer.parseInt(dimensions[2])
            );
        }
    }


    public static final class CircleMatch implements ShapeMatch {
        @Override
        public boolean matches(String line) {
            return line.startsWith("C");
        }

        @Override
        public Shape shape(String line) {
            return new Circle(Integer.parseInt(line.substring(2, line.indexOf(" "))));
        }
    }


    public interface ShapeMapping {
        Shape map(String line);
    }

    public static final class Matches implements ShapeMapping {
        private final Iterable<ShapeMatch> matches;

        public Matches(ShapeMatch... matches) {
            this(Arrays.asList(matches));
        }

        public Matches(Iterable<ShapeMatch> matches) {
            this.matches = matches;
        }

        @Override
        public Shape map(String line) {
            for (ShapeMatch match : matches) {
                if (match.matches(line)) {
                    return match.shape(line);
                }
            }

            throw new RuntimeException("Invalid shape entry line.");
        }
    }
}