2013-07-10 5 views
1

나는 Packet이라는 클래스가 있으며 PacketClientConnecting이라는 클래스는이를 확장합니다. PacketClientConnecting 및 기타 패킷의 인스턴스는 ArrayList<Packet>에 저장됩니다.값에 대한 정적 및 비 정적 액세스

staticnon-static 등의 ID 값에 액세스하려는 경우 (예 : PacketClientConnecting.getStaticId() 또는 packetArrayList.get(5).getId()).

모든 클래스에서 두 함수를 재정의하지 않고 어떻게하면됩니까?

+0

직면 한 실제 문제는 무엇입니까? –

+0

기본 클래스의 목록을 가질 수 있습니까? – NINCOMPOOP

+0

PacketClientConnecting.getStaticId()에 매개 변수가 있습니까? 그 유형은 무엇입니까? getStaticId (x)가 x.getId()를 반환하는 경우에는 재정의하지 않아도됩니다. 그러나 그것은 당신이 성취하려는 것을 확실히 알지 못하기 때문에 추측입니다. – ajb

답변

0

내가이 일을 정말 부드러운 방법이 생각하지 않지만, 하나는 당신이 반사를 사용하여 원하는 것을 얻을 수 있습니다 (한 번만 : 기본 클래스에서) :

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); 
     } 
    } 
} 
관련 문제