Can a variable name be printed?

I created no. constant variables, more than 1000, these constants are unique integers.

public static final FOO 335343 public static final BAR 234234 public static final BEZ 122424 .... .... .... 

Is there a way to print FOO, BAR and BEZ, a name variable in Java? I am not familiar with reflection in Java. I do not know if this helps.

 if ( FOO == 335343) ---> output "FOO" if ( BAR == 234234 ) ---> ouptut "BAR" .... 

Actually, asking this question, I want to write a log to a file

they say

 System.out.println("This time the output is " + FOO); 

and actual conclusion

 This time the output is 335323 

I want to know which variable comes from 335323. Is there any other way, besides putting this variable and its associated constant in hashMap?

thanks

+6
source share
6 answers

There is some β€œspecial case” that may have a workaround for this (which is said by others), but the most important question is: why would you do this (by printing out the variable name)?

In my experience, 99.9% of such questions (how to print the variable name? How to get the variable depends on the user entering the variable name, etc.) are actually raised by the programming novice, and they just made the wrong assumptions and projects. The goal they are trying to achieve can be accomplished with a more suitable design.


Edit

Honestly, I still don't think you are trying to do this, but at least I think the following working answer:

This is more or less a combination of the previous answer:

(Don't try to compile, but at least this gives you an idea)

 class Constants { public static final int FOO = 123; public static final int BAR = 456; private static Map<Integer, String> constantNames = null; public static String getConstantName(int constVal) { if (constantNames == null) { Map<Integer, String> cNames = new HashMap<Integer, String>() for (Field field : MyClass.class.getDeclaredFields()){ if ((field.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) != 0) { && int.class == field.getType()){ // only record final static int fields cNames.put((Integer)field.get(null), field.getName()); } } constNames = cNames; } return constantNames.get(constVal); } } 

Assuming you want a constant name, just do:

 Constants.getConstantName(123); // return "FOO" 
+4
source

You can use something like:

 for (Field field : MyClass.class.getDeclaredFields()){ if (field.getType().toString().equals("int")){ int val = (Integer)field.get(MyClass.this); switch (val){ case 335343: case 234234: System.out.println(field.getName()); } } } 

Remember to change MyClass for your class name and for at least one instance to get the value of the field. So, if you plan to test the code in the main method, you should change MyClass.this to something like new Myclass() . Another thing to keep in mind is that fields are attributes and not method variables (therefore, it will not work if you use this to access variables declared inside a method).

+2
source

As I noted in my comment on the original post, I have a strong suspicion that the best solution for your current problem is to solve this in a completely different way. It seems you want to bind int to String, and one way to do this is to use a map such as HashMap. For instance,

 import java.util.HashMap; import java.util.Map; public class MapDemo { public static void main(String[] args) { Map<Integer, String> myMap = new HashMap<Integer, String>(); myMap.put(335343, "FOO"); myMap.put(234234, "BAR"); myMap.put(122424, "BEZ"); int[] tests = {335343, 234234, 122424, 101010}; for (int i : tests) { // note that null is returned if the key isn't in the map System.out.printf("%d corresponds to %s%n", i, myMap.get(i)); } } } 

Change 1:
In your recent comments and update to the original question, I assume that you have a lot of numbers and related strings involved in this program, and that you need to find the string associated with the number. If so, then you need to think about redesigning that the numbers and their lines should not be hardcoded in your program, but rather be part of the program data, possibly in a text file with one column being numbers and the next column (separated by a space) related text. That way, you can read the data and easily use it in a HashMap, or in a database, or in truly any way you want. This will give your project greater flexibility and reliability.

+2
source

You can use enum .

If these numbers just have to be unique, you can say

 public enum Yourname { FOO, BAR, BEZ } 

and specify the name as Yourname.FOO and the value Yourname.FOO.ordinal() . You can use enumerations for if blocks, switch states.

If you want to have the numbers that you indicated in the question, so if FOO should be 335343 , you can create numbered listings. See is-it-possible-to-assign-numeric-value-to-an-enum-in-java and number-for-each-enum-item .

+1
source

I suggest you print the line number, not the variable name. This should give you enough to determine where the message comes from. Here's more info on how to do this:

How to print line numbers in java log .

0
source

I had a similar problem with a long list of int variables that I had to print the name of each variable and its value (the main goal was to create a text file that would be imported into an Excel file).

Unfortunately, I'm pretty new to Java programming, so the only solution I found (probably wrong) is to use two different arrays: one String array for the String name and another Int array for the corresponding values.

For instance:

 int varName01, varName02, .... String[] listNames = new String {"varName01", "varName02", ..... int[] listValues = new int {varName01, varName02, ..... for (int i=0; i<listValues.length;i++) { print String.format("%s %d", listNames[i], listValues[i]); } 

Perhaps this is not the right way to do this, so any opinion from some Java expert would be more than welcome. Thanks!

0
source

Source: https://habr.com/ru/post/893653/


All Articles