0

In my application, i want to print out a variable´s value AND its name, if possible.

For example:

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);

So i want to read: The int testinteger has a value of 0

Unfortunately, i suppose, it is not possible with primitive types. But is it also the case for types like String, Integer, Boolean etc.? Is there any possibility to get it?

Gary Klasen
  • 1,001
  • 1
  • 12
  • 30
  • 3
    You should really explain why you want to to this. –  May 24 '13 at 23:29
  • @Curtos I don't think it's a duplicate of that question. In this question the *local identifier* in question is in scope and used in scope only. Basically it is asking if it is possible to do `nameOf identifier -> String` or `typeOf identifier -> TypeOrClass`. – user2246674 May 24 '13 at 23:30
  • @RichardJPLeGuen I think that's closer to a duplicate, but the premise of that question still hinges on "reflection". If Java *did* support such `nameOf/typeOf` operators (which it does not), they would operate on the compile-time information and be independent of reflection (much like `obj.class`). – user2246674 May 24 '13 at 23:42

2 Answers2

1

You can't really do this; however, you could use a Map<String,String> to do it in non-dynamic way. The keys would be the type + variable name (you would have to hard code them), and the values would be the actual values associated with those variables (in string form, of course).

Steve P.
  • 14,489
  • 8
  • 42
  • 72
0

Getting a variable name is difficult, but if you use Integer instead of int, you could do something like:

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

If you stick to using classes, and not primitives, you can take advantage of class literals - that is, the .class variable of every object.

ktm5124
  • 11,861
  • 21
  • 74
  • 119