可以使用变量在Java中创建对象吗?

huangapple go评论66阅读模式
英文:

Can variables be used to create object in Java?

问题

如何实现类似这样的功能我想要接受类似 `Circle 10` 或者 `Rectangle 20 30` 这样的命令行参数并创建相应类的对象

class Circle{
    //这里是一些代码
}

class Rectangle{
    //这里是一些代码
}

public class Perimeter{
    public static void main(String[] args) {
        for(int i=0; i<args.length; i++){
            String shape = args[i];
            Shape currShape;

            if(shape.equals("Circle")){
                double radius = Double.parseDouble(args[i+1]);
                currShape = new Circle(radius);
                System.out.println(currShape.getPerimeter());
                i++;
            }
            else if(shape.equals("Rectangle")){
                double length = Double.parseDouble(args[i+1]);
                double width = Double.parseDouble(args[i+2]);
                currShape = new Rectangle(length, width);
                System.out.println(currShape.getPerimeter());
                i += 2;
            }
        }
    }
}

注意:上述代码中的 Shape 类需要根据需要自行定义,并确保 CircleRectangle 类中有计算周长的方法(例如 getPerimeter)。

英文:

How do I do something like this? I want to take command line arguments like Circle 10 or Rectangle 20 30 and create objects of the corresponding classes.

class Circle{
    //Some lines here
}

class Rectangle{
    //Some lines here
}

public class Perimeter{
    public static void main(String[] args) {
        for(int i=0; i&lt; args.length; i++){
            String shape = args[0];
            shape curr_shape = new shape();
            System.out.println(curr_shape.getPerimeter( &lt;arguments&gt; ));
        }
    }
}

答案1

得分: 2

可以使用Class.forName()和反射来创建一个实例,就像@Milgo提议的那样,但我建议创建一个简单的switch/case语句。你的任务看起来像是一些训练,所以这可能是你的最佳选项。

Object form;
switch (type) {
  case "Circle":
    form = new Circle();
    break;
  case "Rectangle":
    form = new Rectangle();
    break;
}
英文:

You can use Class.forName() and reflection to create an instance, like @Milgo proposed, but I would recommend to create a simple switch/case. Your task looks like some training, so probably that would be best option for you.

Object form;
switch (type) {
  case &quot;Circle&quot;:
    form = new Circle();
    break;
  case &quot;Rectangle&quot;:
    form = new Rectangle();
    break;
}

答案2

得分: 1

以下是您要翻译的内容:

虽然您可以使用反射(即黑魔法)来实现,但如果所有形状都具有相同的构造函数签名,比如 List<Double>(其中包括像您的示例中的整数) ,您可以使用最少的代码来完成:

private static Map<String, Function<List<Double>, Shape>> factories = 
    Map.of("Circle", Circle::new, "Rectangle", Rectangle::new); // 等等

public static Shape createShape(String input) {
    String[] parts = input.split(" ");
    String name = parts[0];
    List<Double> dimensions = Arrays.stream(parts)
      .skip(1) // 跳过名称
      .map(Double::parseDouble) // 将字符串转换为双精度数
      .collect(Collectors.toList());
    return factories.get(name).apply(dimensions); // 调用构造函数
}

interface Shape {
    double getPerimeter();
}

static class Rectangle implements Shape {
    private double height;
    private double width;

    public Rectangle(List<Double> dimensions) {
        height = dimensions.get(0);
        width = dimensions.get(1);
    }

    @Override
    public double getPerimeter() {
        return 2 * (height + width);
    }
}

static class Circle implements Shape {
    double radius;

    public Circle(List<Double> dimensions) {
        radius = dimensions.get(0);
    }

    @Override
    public double getPerimeter() {
        return Math.PI * radius * radius;
    }
}
英文:

Although you could use reflection (ie the dark arts), you can do it with minimal code if all shapes have the same constructor signature of say List&lt;Double&gt; (which includes integers like your example):

private static Map&lt;String, Function&lt;List&lt;Double&gt;, Shape&gt;&gt; factories = 
Map.of(&quot;Circle&quot;, Circle::new, &quot;Rectangle&quot;, Rectangle::new); // etc
public static Shape createShape(String input) {
String[] parts = input.split(&quot; &quot;);
String name = parts[0];
List&lt;Double&gt; dimensions = Arrays.stream(parts)
.skip(1) // skip the name
.map(Double::parseDouble) // convert String terms to doubles
.collect(toList());
return factories.get(name).apply(dimensions); // call constructor
}
interface Shape {
double getPerimeter();
}
static class Rectangle implements Shape {
private double height;
private double width;
public Rectangle(List&lt;Double&gt; dimensions) {
height = dimensions.get(0);
width = dimensions.get(1);
}
@Override
public double getPerimeter() {
return 2 * (height + width);
}
}
static class Circle implements Shape {
double radius;
public Circle(List&lt;Double&gt; dimensions) {
radius = dimensions.get(0);
}
@Override
public double getPerimeter() {
return (double) Math.PI * radius * radius;
}
}

huangapple
  • 本文由 发表于 2020年9月24日 13:44:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64040212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定