Get variable name java

How can I print the name of a variable in Java?

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

package Print; public class ClassVariable < void start() < >public static void main(String[] args) < new ClassVariable().start(); >>
package Print; public class ClassVariable < public String testVar; void start() < >public static void main(String[] args) < new ClassVariable().start(); >>
package Print; public class ClassVariable < public String testVar; void start() < ClassVariable newObject = new ClassVariable(); >public static void main(String[] args) < new ClassVariable().start(); >>
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(); >>
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(); >>
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(); >>
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!

Читайте также:  Using wrappers in java

Источник

Is possible to get variable name in java?

send pies

posted 12 years ago

  • Report post to moderator
  • Hi,
    I have two class. I want to get first class variable name. Not value.

    Is possible?
    Help me.
    Thanks in advance.

    Wake up! Don’t let your smile be snatched away by anybody!
    Regards, Eswar

    Sheriff

    send pies

    posted 12 years ago

  • Report post to moderator
  • Via reflection : Class#getFields() will return an array of fields. You can get their name via Field#getName()

    [My Blog]
    All roads lead to JavaRanch

    send pies

    posted 12 years ago

  • Report post to moderator
  • Subhash Kumar
    Attitude is everything

    Источник

    How to get variable name in java class example| getDeclaredFields reflection

    In this example, How to get variable names of a class using reflection.

    Reflection package API in java provides to analyze and update behavior of java classes at runtime.

    class or interface in java contains variables declared with different types and modifiers — public, final, private, default, protected, and static.

    getFields() method of an java.lang.Class gives list of all public aviable variable names of an interface or class in java.

    here is an example of using the getFields method

    import java.lang.reflect.Field; public class Main private Integer privateVariable = 1; public Integer value = 1; public String str = «helloworld»; public static String staticValue = «THIS IS STATIC»; public static final String finalValue = «THIS IS STATIC»; public static void main(String[] args) Main main= new Main(); Class class = main.getClass(); Field[] fields = class.getFields(); for(Field f: fields) System.out.println(f.getName()); > > >

    value str staticValue finalValue

    As you see, only public variable names are retrieved using the getFields() method, and private variables are not displayed.

    How to retrieve private variable names of a class? getDeclaredFields() method of an class returns public ,protected, default and private variable of an class or interface.

    Here is an example to retrieve all fields of a java class

    import java.lang.reflect.Field; public class Main  private Integer privateVariable = 1; public Integer value = 1; public String str = "helloworld"; public static String staticValue = "THIS IS STATIC"; public static final String finalValue = "THIS IS STATIC"; public static void main(String[] args)  Main main= new Main(); Class myclass = main.getClass(); Field[] fields = myclass.getDeclaredFields(); for(Field f: fields) System.out.println(f.getName()); > > >
    privateVariable value str staticValue finalValue

    Источник

    Java Reflection: How to get the name of a variable?

    As of Java 8, some local variable name information is available through reflection. See the «Update» section below.

    Complete information is often stored in class files. One compile-time optimization is to remove it, saving space (and providing some obsfuscation). However, when it is is present, each method has a local variable table attribute that lists the type and name of local variables, and the range of instructions where they are in scope.

    Perhaps a byte-code engineering library like ASM would allow you to inspect this information at runtime. The only reasonable place I can think of for needing this information is in a development tool, and so byte-code engineering is likely to be useful for other purposes too.

    Update: Limited support for this was added to Java 8. Parameter (a special class of local variable) names are now available via reflection. Among other purposes, this can help to replace @ParameterName annotations used by dependency injection containers.

    Solution 2

    It is not possible at all. Variable names aren’t communicated within Java (and might also be removed due to compiler optimizations).

    EDIT (related to comments):

    If you step back from the idea of having to use it as function parameters, here’s an alternative (which I wouldn’t use — see below):

    public void printFieldNames(Object obj, Foo. foos) < ListfooList = Arrays.asList(foos); for(Field field : obj.getClass().getFields()) < if(fooList.contains(field.get()) < System.out.println(field.getName()); >> > 

    There will be issues if a == b, a == r, or b == r or there are other fields which have the same references.

    EDIT now unnecessary since question got clarified

    Solution 3

    (Edit: two previous answers removed, one for answering the question as it stood before edits and one for being, if not absolutely wrong, at least close to it.)

    If you compile with debug information on ( javac -g ), the names of local variables are kept in the .class file. For example, take this simple class:

    After compiling with javac -g:vars TestLocalVarNames.java , the names of local variables are now in the .class file. javap ‘s -l flag («Print line number and local variable tables») can show them.

    javap -l -c TestLocalVarNames shows:

    class TestLocalVarNames extends java.lang.Object< TestLocalVarNames(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."":()V 4: return LocalVariableTable: Start Length Slot Name Signature 0 5 0 this LTestLocalVarNames; public java.lang.String aMethod(int); Code: 0: ldc #2; //String a string 2: astore_2 3: new #3; //class java/lang/StringBuilder 6: dup 7: invokespecial #4; //Method java/lang/StringBuilder."":()V 10: astore_3 11: aload_3 12: aload_2 13: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 16: iload_1 17: invokevirtual #6; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder; 20: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String; 23: areturn LocalVariableTable: Start Length Slot Name Signature 0 24 0 this LTestLocalVarNames; 0 24 1 arg I 3 21 2 local1 Ljava/lang/String; 11 13 3 local2 Ljava/lang/StringBuilder; > 

    The VM spec explains what we’re seeing here:

    The LocalVariableTable attribute is an optional variable-length attribute of a Code (§4.7.3) attribute. It may be used by debuggers to determine the value of a given local variable during the execution of a method.

    The LocalVariableTable stores the names and types of the variables in each slot, so it is possible to match them up with the bytecode. This is how debuggers can do «Evaluate expression».

    As erickson said, though, there’s no way to access this table through normal reflection. If you’re still determined to do this, I believe the Java Platform Debugger Architecture (JPDA) will help (but I’ve never used it myself).

    Solution 4

    import java.lang.reflect.Field; public class test < public int i = 5; public Integer test = 5; public String omghi = "der"; public static String testStatic = "THIS IS STATIC"; public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException < test t = new test(); for(Field f : t.getClass().getFields()) < System.out.println(f.getGenericType() +" "+f.getName() + " btn btn-outline-primary" role="button" data-toggle="collapse" aria-expanded="false" aria-controls="moreSolutions" href="#moreSolutions">View more solutions 
    Share:
    292,153

    Related videos on Youtube

    How to get the generic variable types using Java Reflection? | Reflection in java 02 : 11
    How to get the generic variable types using Java Reflection? | Reflection in java
    Ram N Java
    492
    Java Reflection Tutorial 28 : 33
    Java Reflection Tutorial
    Derek Banas
    217
    How to access the variable Annotation using Java Reflection? | Reflection in java 02 : 48
    How to access the variable Annotation using Java Reflection? | Reflection in java
    Ram N Java
    150
    Variables in Java ✘【12 minutes】 12 : 32
    Variables in Java ✘【12 minutes】
    Bro Code
    38
    One Rule to Name Methods/Variables Clearly 06 : 45
    One Rule to Name Methods/Variables Clearly
    Laravel Daily
    14
    Java Tutorial - Reflection Basics 28 : 02
    Java Tutorial - Reflection Basics
    Kody Simpson
    11
    David Koelle
    Author by

    David Koelle

    I create usable software products from new ideas. Author of JFugue (Java API for music programming), experienced presenter, proponent of awesome user interfaces, project manager. Starting at age 7, cut my programming teeth on the TRS-80 and TI-99/4A, then went on to Commodore 64 and Commodore 128. Was a big fan of RUN Magazine. Evolved from BASIC to Turbo Pascal, in which I wrote my own UI framework. Professional experience includes a range of languages, primarily Java. Branching into Android, Scala, and HTML5/CSS3/JavaScript. On Twitter: http://www.twitter.com/dkoelle

    Updated on February 26, 2020

    Comments

    David Koelle
    David Koelle over 3 years

    Using Java Reflection, is it possible to get the name of a local variable? For example, if I have this:

    Foo b = new Foo(); Foo a = new Foo(); Foo r = new Foo(); 

    is it possible to implement a method that can find the names of those variables, like so:

    EDIT: This question is different from Is there a way in Java to find the name of the variable that was passed to a function? in that it more purely asks the question about whether one can use reflection to determine the name of a local variable, whereas the other question (including the accepted answer) is more focused on testing values of variables.

    All great answers! Thanks to everyone for replying and commenting - this has been an interesting and insightful discussion.

    Источник

    How to get fields(variables) name and type of class using Reflection?

    Java Reflection

    Reflection API is used to interact, examine or modify run-time behavior of programs running in the Java virtual machine. Reflection is bit costly so use it only when you have no other options left. Today we'll see how you can get name and type of fields(variables) declared in class.

    Source Code
    I've created some sample beans for example.

    /* Actor.java */ import java.util.List; import java.util.Map; import java.util.Set; public class Actor < private long id; private String Name; private SetFilms; private List LanguageSpeaks; private Map dummyMap; > /* Film.java */ public class Film < private long id; private String Name; >/* Language.java */ public class Language

    import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; public class ClassFieldsReflection < public static void main(String[] args) < ClassFieldsReflection objClassFieldsReflection = new ClassFieldsReflection(); objClassFieldsReflection.AccessFieldsUsingReflection(new Actor()); >/** * Access fields of Object using Reflection. * @param obj */ private void AccessFieldsUsingReflection(Object obj)< /* Get array of fields declared in Class */ Field[] fields = obj.getClass().getDeclaredFields(); /* Loop through all fields */ for(int i = 0; i < fields.length ; i++)< /* Get field name */ String fieldName = fields[i].getName(); /* Get generic/base type of field (int, short, long, String, etc. ) */ Object fieldType = fields[i].getGenericType(); System.out.println("Field(variable) name: " + fieldName); System.out.println("Generic Type: " + fieldType); /* Set, List and Map are ParameterizedType */ if(fieldType instanceof ParameterizedType)< /** * This will give you Actual Type of Set, List and Map. * Example: * List -> String is ActualType * Set -> Integer is ActualType * Map -> String, Long is ActualType */ System.out.println("Actual Type:"); for(Object objActualType : ((ParameterizedType) fieldType).getActualTypeArguments()) < System.out.println("-- "+objActualType); >> System.out.println("+++++++++++++++++++++++++++++++"); > > >
    Field(variable) name: id Generic Type: long +++++++++++++++++++++++++++++++ Field(variable) name: Name Generic Type: class java.lang.String +++++++++++++++++++++++++++++++ Field(variable) name: Films Generic Type: java.util.Set Actual Type: -- class javaQuery.beans.Film +++++++++++++++++++++++++++++++ Field(variable) name: LanguageSpeaks Generic Type: java.util.List Actual Type: -- class javaQuery.beans.Language +++++++++++++++++++++++++++++++ Field(variable) name: dummyMap Generic Type: java.util.Map Actual Type: -- class java.lang.String -- class java.lang.Long +++++++++++++++++++++++++++++++ 

    Источник

    Оцените статью