【问题标题】:Constructor call with varibales without quoting the explicit classtype in Java?使用变量调用构造函数而不引用Java中的显式类类型?
【发布时间】:2014-01-19 01:40:44
【问题描述】:

有没有可能用变量实例化一个类而不显式调用对象的类类型?

例如,我们有一个 cat 类和一个代表 String cat 的字符串。是否可以在代码中调用如下或类似的类 cat?

public class MyMainClass {

 public static void main(String[] args) {

     String name="cat";

     //normal methode of instancing the class Cat:
     Cat cat=new Cat();

     //my method
     name cat=new name(); // because name="cat" this should be Cat cat=new Cat(); 

     }
}


class Cat{
// whatsoever
}

【问题讨论】:

  • 你的用例是什么?
  • String name=new String("cat"); 是一种浪费。就做String name="cat"
  • 使用反射或泛型可以沿着这些思路完成一些事情,不过,在我提出任何建议之前,我需要更多关于您尝试做什么以及为什么尝试做的细节。
  • 我认为你有一个经典的XY Problem 继续在这里。

标签: java variables constructor call


【解决方案1】:

使用反射:

String nameString = "com.example.Test";
Class name = Class.forName(nameString);
Object instance = name.newInstance();
Test test; // Defined if is instanceof Test

if(instance instanceof Test) {
    // Yeah! now you can do this: test = (Test)instance; and something else...
}

注意:您必须在字符串中输入整个包名。

【讨论】:

    【解决方案2】:

    你可以使用反射:

    String name = "com.foo.Cat"; // Note fully qualified name
    Object object = Class.forName(name).newInstance();
    

    但你不会知道你有什么类型,除非你使用instanceof

    并且name 的值不能用于创建该名称的变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 2017-01-28
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      相关资源
      最近更新 更多