TL;DR This is an interesting programming challenge, but I find very little use for this in real life scenarios.
Here the name of the first string variable is known before hand, you can directly store the final value in this instead of the round-about way of storing the name of second variable.
If understand correctly you are trying to access a (String) variable of a class whose name will be in another string variable. This is possible using java reflection.
Additionally you want this code to be placed in an interface such that it can be (re)used in all the classes implementing it.
import java.lang.reflect.Field;
interface Foo {
public default String getStringVar()
throws NoSuchFieldException, IllegalAccessException {
// get varName
Class thisCls = this.getClass();
Field varNameField = thisCls.getField("varName");
String varName = (String) varNameField.get(this);
// get String variable of name `varName`
Field strField = thisCls.getField(varName);
String value = (String) strField.get(this);
return value;
}
}
class FooImpl1 implements Foo {
public final String varName = "str1";
public String str1 = "some value";
}
class FooImpl2 implements Foo {
public final String varName = "str2";
public String str2 = "some other value";
}
class Main {
public static void main(String[] args)
throws NoSuchFieldException, IllegalAccessException {
System.out.println(new FooImpl1().getStringVar());
System.out.println(new FooImpl2().getStringVar());
}
}
Here I have two String members in classes implementing interface Foo
. The first varName
contains the variable name of the second String, second String variable contains the data.
In the interface using reflection I am first extracting the variable name stored in varName
, then using this extracting the value of second String.