2012-03-10 2 views
5

에 의해 사용되는 :내가 엄청나게 많은 시간이 약이 구조를 가진 파서가 instanceof를

if (tokens.first() instanceof CommaToken) { 
    tokens.consume(); 
나는이 수행하는 방법을 알고 싶습니다

:

if (match(CommaToken)) { ... blah ... } 

private boolean match(??? tokenType) { 
    if (tokens.first() instanceof tokenType) { ... blah ... } 
} 

내가 ' m에 wetware 실패가 발생하여 메서드의 tokenType 클래스를 알아낼 수 없습니다. 또 다른 문제점은 Java가 'tokenType'을 리터럴로 취급한다는 것입니다. 즉 :

instanceof tokenType 

구문에 대한 단지

instanceof CommaToken 

것 같습니다.

아이디어가 있으십니까?

답변

8

당신은 (인스턴스에서 클래스 개체를 가져)과 getClass() (클래스 클래스 참조에서 객체를 얻기 위해) class를 통해 Class 객체를 사용하여이 작업을 수행 할 수 있습니다 :

if (match(CommaToken.class)) { ... blah ... } 

private boolean match(Class<?> klass) { 
    if (tokens.first().getClass().equals(klass)) { ... blah ... } 
} 
+4

기술적으로의 동적 동등한 'instanceof'는 [Class # isInstance (Object)']이어야합니다 (http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#isInstance (java. lang.Object)) –