pre-knowledge
In short
You can’t print just the name of a variable. However, I can show you a way to print the name of a class variable.
(AKA if you want to print the name of a variable, make it a class variable)
explanation
- create a standard main class structure
package Print;
public class ClassVariable {
void start() {
}
public static void main(String[] args) {
new ClassVariable().start();
}
}
- Create a class variable, PUBLIC CLASS VARIABLE!!
package Print;
public class ClassVariable {
public String testVar;
void start() {
}
public static void main(String[] args) {
new ClassVariable().start();
}
}
- Create an object of your class
package Print;
public class ClassVariable {
public String testVar;
void start() {
ClassVariable newObject = new ClassVariable();
}
public static void main(String[] args) {
new ClassVariable().start();
}
}
- Create a Class Object
package Print;
public class ClassVariable {
public String testVar;
void start() {
ClassVariable newObject = new ClassVariable();
Class newClassObject = newObject.getClass();
}
public static void main(String[] args) {
new ClassVariable().start();
}
}
- import the Field class
- If we save the variable in a Field variable we can get information about the variable that we had saved in the class
package Print;
import java.lang.reflect.Field;
public class ClassVariable {
public String testVar;
void start() {
ClassVariable newObject = new ClassVariable();
Class newClassObject = newObject.getClass();
Field variable = newClassObject.getField("testVar");a
}
public static void main(String[] args) {
new ClassVariable().start();
}
}
- Now you get an error so add the throw declarations to all linked methods or add a try and catch statement
package Print;
import java.lang.reflect.Field;
public class ClassVariable {
public String testVar;
void start() throws NoSuchFieldException, SecurityException {
ClassVariable newObject = new ClassVariable();
Class newClassObject = newObject.getClass();
Field variable = newClassObject.getField("testVar");
}
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
new ClassVariable().start();
}
}
- Now we just use the class PrintStream to print the name of the variable
package Print;
import java.lang.reflect.Field;
public class ClassVariable {
public String testVar;
void start() throws NoSuchFieldException, SecurityException {
ClassVariable newObject = new ClassVariable();
Class newClassObject = newObject.getClass();
Field variable = newClassObject.getField("testVar");
System.out.println("The name of the variable is: " + variable.getName());
}
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
new ClassVariable().start();
}
}
YOU HAVE PRINTED THE NAME OF A VARIABLE!