Can you get the name of a variable in Java? [duplicate]

4

I'm doing a test code and in it I need to get the name of the variable, not the value of it , but I can not find a way to do it.

NOTE: What I want to get is the name I gave the variable, not the name of the Class , which in the case of the example would be the String Class .

If I have this:

String sPedro = new String ("Pedro");
String sPablo = new String ("Pedro");

I want to know how to get the values sPedro and sPablo , it would be like applying a kind of method getName() something like this:

//Este código no funciona
System.out.println(sPedro.getName());
System.out.println(sPablo.getName());

Result

sPedro
sPablo
    
asked by A. Cedano 02.05.2017 в 17:12
source

1 answer

4

If I understand your question well, "but for the comments it makes me doubt", from Java 8 you can make use of the reflection.

use:

  • import java.lang.reflect.Field;
  • .getName()
/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

import java.lang.reflect.Field;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public String sPedro = new String ("Pedro");
    public String sPablo = new String ("Pedro");

    public static void main (String[] args) throws java.lang.Exception, java.lang.IllegalArgumentException, java.lang.IllegalAccessException
    {

     Ideone t = new Ideone();
     for(Field f : t.getClass().getFields()) {

      System.out.println("nombre: " + f.getName());
     }
  }
}

Test Ideone

  

UPDATE: added by comment on exactly what you want to do.

Well according to your comment ... What I want to get are the values sPedroy sPablo ... - > sPedro.getName() I imagine that .getName() is a getter in the class, at this time it would be confusing to use that method name for the following example, since Field has a similar name, so that it is more likely I have changed .getName() getNombre() that returns the value of the variable test that contains the name that is assigned from the constructor in the initialization.

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception, java.lang.IllegalArgumentException, java.lang.IllegalAccessException
    {

         Ideone i = new Ideone();
         Init test = i.new Init();

         for(Field f : test.getClass().getFields()) {

            System.out.println("nombre instancia : " + f.getName());

            if (f.getType() == Test.class) {

                Class<?> clazz = Ideone.Test.class;
                Method method = clazz.getMethod("getNombre");
                Ideone.Test typ = (Ideone.Test)f.get(test);

                method.invoke(typ);

                System.out.println("nombre que contiene la variable test : " + typ.getNombre());
            }
         }
      }

      private class Init{

        public Test sPedro = new Test("Pedro");
        public Test sPablo = new Test("Pablo");


      }
      private class Test{

        String test;

        public Test(String nombre){
            test = nombre;
        }
        public String getNombre(){
            return test;
        }
      }
    }

Test Ideone

stdout:

nombre instancia : sPedro
nombre que contiene la variable test : Pedro
nombre instancia : sPablo
nombre que contiene la variable test : Pablo

in this line Method method = clazz.getMethod("getNombre"); getName is the name of the method that we are going to invoke later, which refers to the name of the getter in the class.

then in this other line method.invoke(typ); invoke the method passing the instance, in the documentation that I leave at the end, you can go deeper if you want to spend passes ect. invoke(Object obj, Object ... args) would be in the second parameter.

NOTE: After reading again I imagined and imagined that the class String used was to simulate a more complex class, because now I have that doubt, if the variables are String and what you want is the value is much simpler than the previous you just have to use the following:

for(Field f : t.getClass().getFields()) {

  System.out.println("nombre: " + (String)f.get(t));

}

If the class has other types of variables than String can use if (f.getType() == String.class) {

Documentation may be useful to you:

link

    
answered by 02.05.2017 / 17:55
source