【问题标题】:Getting names and or types of variables in java possible? [duplicate]可以在 java 中获取变量的名称和/或类型吗? [复制]
【发布时间】:2013-05-24 23:26:03
【问题描述】:

在我的应用程序中,如果可能,我想打印出变量的值及其名称。

例如:

int testinteger = 0;
String type = > type of testinteger? (int);
String name = > name of testinteger? (testinteger);


System.out.println("The "+type+" "+name+" has a value of"+ testinteger);

所以我想阅读:int testinteger 的值为 0

不幸的是,我想,原始类型是不可能的。但对于StringIntegerBoolean 等类型,情况也是如此吗?有没有可能得到它?

【问题讨论】:

  • 你应该真正解释你为什么要这样做。
  • @Curtos 我不认为这是该问题的重复。在这个问题中,所讨论的 本地标识符 在范围内并且仅在范围内使用。基本上它是在询问是否可以做nameOf identifier -> StringtypeOf identifier -> TypeOrClass
  • @RichardJPLeGuen 我认为这更接近于重复,但该问题的前提仍然取决于“反思”。如果 Java 确实 支持这样的nameOf/typeOf 运算符(它不支持),它们将在编译时信息上进行操作并且独立于反射(很像obj.class)。

标签: java


【解决方案1】:

你真的不能这样做;但是,您可以使用Map<String,String> 以非动态方式执行此操作。键是类型 + 变量名(您必须对它们进行硬编码),值是与这些变量关联的实际值(当然是字符串形式)。

【讨论】:

    【解决方案2】:

    获取变量名很困难,但如果您使用 Integer 而不是 int,您可以执行以下操作:

    Integer testInteger = 1;
    String type = testInteger.class.getName();
    System.out.println(type);
    

    如果您坚持使用类而不是原语,则可以利用类文字 - 即每个对象的 .class 变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      • 2018-07-30
      • 2017-08-06
      相关资源
      最近更新 更多