내가이 일을 정말 부드러운 방법이 생각하지 않지만, 하나는 당신이 반사를 사용하여 원하는 것을 얻을 수 있습니다 (한 번만 : 기본 클래스에서) :
class Packet {
public static int getStaticId() {
return 1;
}
// This method is virtual and will be inherited without change
public int getId() {
try {
// Find and invoke the static method corresponding
// to the run-time instance
Method getStaticId = this.getClass().getMethod("getStaticId");
return (Integer) getStaticId.invoke(null);
// Catch three reflection-related exceptions at once, if you are on Java 7+,
// use multi-catch or just ReflectiveOperationException
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
을 이제 서브 클래스의 모든
class PacketClientConnecting extends Packet {
public static int getStaticId() {
return 2;
}
}
의 그것을 테스트 해보자 :
class Main {
public static void main(String[] args) {
// Both print 1
System.out.println(Packet.getStaticId());
System.out.println(new Packet().getId());
// Both print 2
System.out.println(PacketClientConnecting.getStaticId());
System.out.println(new PacketClientConnecting().getId());
}
}
당신이 피하고 싶은 경우에 당신은) getStaticId를 (정의입니다 필요 getId()를 호출 할 때마다 반사 작업을 호출하는 오버 헤드로 인해 기본 클래스의 필드를 사용하여 ID를 캐시 할 수 있습니다.
class Packet {
public static int getStaticId() {
return 1;
}
private final int id = computeId();
public int getId() {
return id;
}
// This method runs once per instance created
private int computeId() {
try {
Method getStaticId = this.getClass().getMethod("getStaticId");
return (Integer) getStaticId.invoke(null);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
직면 한 실제 문제는 무엇입니까? –
기본 클래스의 목록을 가질 수 있습니까? – NINCOMPOOP
PacketClientConnecting.getStaticId()에 매개 변수가 있습니까? 그 유형은 무엇입니까? getStaticId (x)가 x.getId()를 반환하는 경우에는 재정의하지 않아도됩니다. 그러나 그것은 당신이 성취하려는 것을 확실히 알지 못하기 때문에 추측입니다. – ajb