I want to do something like this:
public class Parent {
private static final Map<Class<?>, Object> map;
static {
map = new IdentityHashMap<>();
}
public Parent() {
if (map.get(getKey()) == null) {
map.put(getKey(), new Object());
}
}
private static Class<?> getKey() {
return /*something*/;
}
public static Object getValue() {
return map.get(getKey());
}
}
public class Child extends Parent {
}
Child.getValue() // returns an object
Parent.getValue() // returns other object
I tried to use MethodHandles.lookup().lookupClass() in getKey(), but it returns Parent class when calling Child.getValue() (eg:
public class Parent {
private static final Map<Class<?>, Object> map;
static {
map = new IdentityHashMap<>();
}
public Parent() {
if (map.get(getKey()) == null) {
map.put(getKey(), new Object());
}
}
private static Class<?> getKey() {
Class<?> clazz = MethodHandles.lookup().lookupClass();
System.out.println(clazz.getName());
return clazz;
}
public static Object getValue() {
return map.get(getKey());
}
}
public class Child extends Parent {
}
Child.getValue()
// console output: my.project.package.Parent
// i want: my.project.package.Child
)
How i can do this? I tried to use all cases from this: Getting the class name from a static method in Java, and in every case it prints in console parent class name.
UPD: the getValue() method should be static, i can't do anything with it. UPD2: I know that such code is bad practice, and I know why this problem arises, but I did not write the getValue() method and it does not depend on me, and I want to find out any way to perform the task described in the question, even using reflection, the MethodHandles or something else