Отправка статических методов на общих типахJAVA

Программисты JAVA общаются здесь
Anonymous
Отправка статических методов на общих типах

Сообщение Anonymous »

Я хочу достичь чего-то вроде

Код: Выделить всё

interface Parent {
static int hi() { return 1; }
}

class Child implements Parent {
static int hi() { return 0; }
}

class Child2 implements Parent {
static int hi() { return 3; }
}

class Connector {
int getHi() { return T.hi(); }
}

class Main {
public static void main(String[] args) {
Connector c = new Connector();
System.out.println(c.getHi()); // want it to print 0, but prints 1

Connector c2 = new Connector();
System.out.println(c2.getHi()); // want it to print 3, but prints 1
}
}
, где тип может быть выведен с помощью системы типа Java, и в результате вызовите правильный метод gethi () .

Код: Выделить всё

interface Parent {}

class Child implements Parent {
static int hi() { return 0; }
}

class Child2 implements Parent {
static int hi() { return 3; }
}

class Connector {
static  int getHi(Class classType) {
try {
return (int) MethodHandles.lookup().findStatic(classType, "hi", MethodType.methodType(int.class)).invokeExact();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}

class Main {
public static void main(String[] args) {
System.out.println(Connector.getHi(Child.class)); // prints 0
System.out.println(Connector.getHi(Child2.class)); // prints 3
}
}
В идеале я хотел бы переместить это на что -то вроде первого варианта, где я обрабатываю статический метод, вызывая во время компиляции (так как методики. Есть ли способ сделать что -то вроде первого варианта?

Подробнее здесь: https://stackoverflow.com/questions/796 ... eric-types

Вернуться в «JAVA»