i want to display only the variable name not the value let's say
String x='abc';
i want my output to be x
notabc
don't want to create a code like this
System.out.println('x')
i want dynamicaly save the variable name in another variable and display it like if there's a built in function to do this like for example i know this function doesn't exist but lets say it exists
System.out.println(x.getVariableName()) //output x
i want a something like that
You can't. When you compile a java program in java bytecode, the information about variable names are not included.
For example:
File Main.java
public class Main
{
public static void main(String[] args) {
String x = "abc";
System.out.println(x);
}
}
compiled in Main.class
(there are many more "characters" you cannot see):
Êþº¾ =
java/lang/Object <init> ()V abc
java/lang/System out Ljava/io/PrintStream;
java/io/PrintStream println (Ljava/lang/String;)V Main Code LineNumberTable main ([Ljava/lang/String;)V
SourceFile Main.java ! *· ± + L² +¶ ±
If you try to use a decompiler to decompile the bytecode, that's what you'd get:
import java.io.PrintStream;
public class Main
{
public static void main(String[] paramArrayOfString)
{
String str = "abc";
System.out.println(str);
}
}
As you can see, there is no information about any variable names.
The simplest reason behind this is that this information is completely useless to the runtime, it is only useful to programmers when they're writing code, to give a meaning of what they're coding and keep track of the business logic.