It is slightly unclear what you want, but my best guess is that you are referring to reflection.
Reflection gets its name from the idea that the code "looks at its reflection in a mirror", i.e. code looking at itself. The java reflection API is incredibly powerful, and allows you to do things possible impossible using other techniques, but it has major drawbacks.
For example:
public class MyClass {
public int x;
}
public String getMethodName() {
Class clazz = MyClass.class;
return clazz.getFields()[0];
}
public void setField(int newValue) {
Class clazz = MyClass.class;
clazz.getFields()[0].setInt(newValue);
}
The above code:
- defines a basic class
- provides a method to get the name of the first field
- provides a method to set the value of this field.
This seems to be what you are asking about.
However, there are serious downsides to using reflection.
- It is very slow, up to 1000x slower, as the JVM is less able to make optimisations, since it has less information about the data it is working with at compile time.
- It introduces the possibility for very nasty bugs. Once you open this can of worms, you can no longer confidently make assumptions about your code that you would before. If you have a class with a private variable with no setters, you might assume its value cannot be changed. Using reflection, it can.
- It ignores Java's type checking system. This is one reason for the slowness mentioned above, since type checking must be done at runtime rather than compile-time. However, it also opens you up to type errors in a major way again, the entire thing Java's type system tries to save you from.
Because of this, reflection should only be used when there are literally no alternatives, for example, making a Json parsing library, writing an ORM system, etc. In other situtations, I have found that generally problems that seem to be reflection problems are actually abstraction problems.
Perhaps if, instead of getting a field by its String
name, you could create an interface called ContainsMyField
with a method called getMyField()
, and any class that you expect to have this field should implement this interface. This option is much cleaner, faster, and safer.