I have a variable that contains the name of another variable. I intend to read the contents of the variable name. how?

Dani AI

Generated

Short answer: use the Reflection API to look up a Field by name at runtime, or — preferably — change the design so values are stored in a map or exposed by a lookup method.

was right to question the indirection, and pointed you toward reflection. A minimal, practical pattern (for instance fields) is to find the declared field, make it accessible if needed, then read its value. Handle the usual exceptions and remember the value returned is an Object (primitives are boxed).

import java.lang.reflect.Field;

static Object readFieldByName(Object target, String fieldName) throws ReflectiveOperationException {
    Field f = target.getClass().getDeclaredField(fieldName);
    f.setAccessible(true);
    return f.get(target);
}

Notes and cautions:

  • Using the Class API that enumerates fields will normally show only public/inherited fields; use declared-field lookup to reach private fields declared on the class.
  • For static fields call f.get(null); for instance fields pass the instance.
  • Catch or declare NoSuchFieldException and IllegalAccessException (or use ReflectiveOperationException).
  • Reflection is slower, breaks encapsulation, and may be blocked by security managers or the Java module system (Java 9+). In modern Java, modules can prevent reflective access to private members — consider VarHandles or module exports if you must.
  • If you control the code, prefer a Map<String,Object>, an explicit getter (e.g., get(String name)), or JavaBean property access. Those are safer, clearer, and easier to maintain than reflective field access.

This approach gives the immediate solution while highlighting safer, long-term alternatives.

Recommended Answers

All 4 Replies

So is your setup like this:

String variableName = "aVariable";
int aVariable = 670;

And you want to access aVariable through variableName? If that's the case, why do you need variableName?

And you want to access aVariable through variableName? If that's the case, why do you need variableName?

Yes. Because aVariable derived from the results of an operation of reading the contents of the field from a class.

getClass().getFields();

tank you......

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.