클래스 B와 클래스가 클래스를 C확장 A하고 유형의 객체를 가지고 B있거나 C인스턴스 인 유형을 어떻게 알 수 있습니까?
클래스 B와 클래스가 클래스를 C확장 A하고 유형의 객체를 가지고 B있거나 C인스턴스 인 유형을 어떻게 알 수 있습니까?
답변:
if (obj instanceof C) {
//your code
}
if(!(obj instanceof C))
code Child1 child1 = new Child1 ()을 시도하십시오 . Parent1 parentChild = 새 Child2 (); Child2 child2 = 새로운 Child2 (); (Parent1의 자식 1 인스턴스); (Child1의 child1 인스턴스); (Child2의 parentChild 인스턴스); (Parent1의 parentChild 인스턴스); (Child1의 parentChild 인스턴스); code 그것은 instanceof의 의도를 분명히 할 수 있습니다.
여러 정답이 제시되었지만 여전히 더 많은 방법이 있습니다. Class.isAssignableFrom()단순히 객체를 캐스트하려고 시도하면 (을 던질 수 있음 ClassCastException).
객체 obj가 유형의 인스턴스 인지 테스트하는 가능한 방법을 요약 해 보겠습니다 C.
// Method #1
if (obj instanceof C)
;
// Method #2
if (C.class.isInstance(obj))
;
// Method #3
if (C.class.isAssignableFrom(obj.getClass()))
;
// Method #4
try {
C c = (C) obj;
// No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}
// Method #5
try {
C c = C.class.cast(obj);
// No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}
null취급상의 차이null그러나 처리 에는 차이가 있습니다 .
false경우 obj이다 null( null아무것도의 인스턴스가 아닌).NullPointerException분명히 던질 것 입니다.null있기 때문에 수락 null합니다!기억하기 :
null아니다 모든 유형의 인스턴스 있지만 캐스트 할 수 있는 유형.
Class.getName()객체가 유형이 아닌 하위 클래스 인 경우 "is-instance-of" 테스트 베스 케이스 를 수행하는 데 사용해서는 안됩니다 C. 완전히 다른 이름과 패키지를 가질 수 있습니다 (따라서 클래스 이름이 분명히 일치하지 않음). 여전히 유형 C입니다.Class.isAssignableFrom()는 대칭 이 아닙니다 : 의 유형 이의 서브 클래스 인 경우 obj.getClass().isAssignableFrom(C.class)반환 false됩니다 .objC당신이 사용할 수있는:
Object instance = new SomeClass();
instance.getClass().getName(); //will return the name (as String) (== "SomeClass")
instance.getClass(); //will return the SomeClass' Class object
HTH. 그러나 대부분의 경우 제어 흐름이나 이와 유사한 것에 사용하는 것이 좋지 않습니다 ...
제안 된 방법 중 하나를 사용하는 것은 잘못된 OO 설계에 기반한 코드 냄새로 간주됩니다.
당신의 디자인이 좋은 경우에, 당신은 자신이 사용할 필요 찾을 안 getClass()나 instanceof.
제안 된 방법 중 하나는 디자인 측면에서 명심해야 할 것입니다.
이 경우에는 반사를 사용할 수 있습니다
objectName.getClass().getName();
예:-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getClass().getName();
}
이 경우 객체가 HttpServletRequest인터페이스 참조 변수에 전달하는 클래스의 이름을 얻습니다 .
obj.getClass()하면 className, prefixex라는 단어가 반환됩니다class
request.getClass().getName();모든 패키지를 인쇄합니다! 클래스 이름과 함께
.isInstance" Class"클래스 에도 메소드 가 있습니다 . via myBanana.getClass()를 통해 객체의 클래스를 얻는 다면 객체 myApple가 myBananavia 와 동일한 클래스의 인스턴스 인지 확인할 수 있습니다
myBanana.getClass().isInstance(myApple)
Java 8 제네릭을 사용하여 스위치 케이스를 사용하지 않고 런타임에 객체 인스턴스를 얻었습니다.
public <T> void print(T data) {
System.out.println(data.getClass().getName()+" => The data is " + data);
}
모든 유형의 데이터를 전달하면 메소드는 호출하는 동안 전달한 데이터 유형을 인쇄합니다. 예 :
String str = "Hello World";
int number = 10;
double decimal = 10.0;
float f = 10F;
long l = 10L;
List list = new ArrayList();
print(str);
print(number);
print(decimal);
print(f);
print(l);
print(list);
다음은 출력입니다
java.lang.String => The data is Hello World
java.lang.Integer => The data is 10
java.lang.Double => The data is 10.0
java.lang.Float => The data is 10.0
java.lang.Long => The data is 10
java.util.ArrayList => The data is []