instanceof
kann verwendet werden, um zu testen, ob ein Objekt eine direkte oder eine absteigende Instanz einer bestimmten Klasse ist. instanceof
kann auch mit Schnittstellen verwendet werden, obwohl Schnittstellen nicht wie Klassen instanziiert werden können. Kann jemand erklären, wie instanceof
funktioniert?
Zunächst können wir instances
von Klassen speichern, die eine bestimmte interface
in einem interface reference variable
wie folgt implementieren.
package com.test;
public class Test implements Testeable {
public static void main(String[] args) {
Testeable testeable = new Test();
// OR
Test test = new Test();
if (testeable instanceof Testeable)
System.out.println("instanceof succeeded");
if (test instanceof Testeable)
System.out.println("instanceof succeeded");
}
}
interface Testeable {
}
dh jede Laufzeitinstanz, die eine bestimmte Schnittstelle implementiert, besteht den instanceof
-Test
EDIT
und die Ausgabe
instanceof succeeded
instanceof succeeded
@ RohitJain
Sie können Instanzen von Schnittstellen erstellen, indem Sie anonyme innere Klassen wie diese verwenden
Runnable runnable = new Runnable() {
public void run() {
System.out.println("inside run");
}
};
und Sie testen, dass die Instanz vom Typ interface ist und den instanceof
-Operator wie folgt verwendet
System.out.println(runnable instanceof Runnable);
und das Ergebnis ist "wahr"
object instanceof object_interface
ergibt true
.
Sie führen eine instanceof
-Prüfung einer reference
gegen eine instance
durch und prüfen den Typ von instance
, auf den die bestimmte reference
zeigt.
Da Sie nun eine Referenz einer interface
erstellen können, die auf eine Instanz der Implementierung von class
verweist (dasselbe Konzept wie Super class reference
auf subclass instance
). Sie können also eine instanceof
-Überprüfung durchführen.
Für z. B .: -
public interface MyInterface {
}
class ImplClass implements MyInterface {
public static void main(String[] args) {
MyInterface obj = new ImplClass();
System.out.println(obj instanceof ImplClass); // Will print true.
}
}
- Zunächst wird mit instanceof verglichen, ob die Objektreferenzvariable, die das Objekt enthält, einen bestimmten Typ hat oder nicht.
Z.B:
public void getObj(Animal a){ // a is an Object Reference Variable of type Animal
if(a instanceof Dog){
}
}
- Im Fall von interface
kann die class
, die implementiert, mit instanceof
verwendet werden.
Z.B:
public interface Brush{
public void Paint();
}
public class Strokes implements Brush{
public void Paint(){
System.out.println("I am painting");
}
}
public class Test{
public static void main(String[] args){
Brush b = new Strokes();
if(b instanceof Strokes){
b.Paint();
}
}
}
hi Das Folgende wird True für die InstanzOf ergeben:
• If S is an ordinary (nonarray) class, then:
• If T is a class type, then S must be the same class as T, or S must be a subclass of T;
• If T is an interface type, then S must implement interface T.
• If S is an interface type, then:
• If T is a class type, then T must be Object.
• If T is an interface type, then T must be the same interface as S or a superinterface of S.
• If S is a class representing the array type SC[], that is, an array of components of type SC, then:
• If T is a class type, then T must be Object.
• If T is an interface type, then T must be one of the interfaces implemented by arrays (JLS §4.10.3).
• If T is an array type TC[], that is, an array of components of type TC, then one of the following must be true:
- TC and SC are the same primitive type.
- TC and SC are reference types, and type SC can be cast to TC by these run-time rules
Bitte gehen Sie zu diesem Link, um eine klare Vorstellung zu haben:
http://docs.Oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.instanceof
public class Programmers {
public static boolean hasReallife(Programmer programmer) {
return programmer instanceof Reallife; ══════════════════╗
} ║
║
} ║
▼
public class ReallifeProgrammer extends Programmer implements Reallife {
public ReallifeProgrammer() {
diseases.get("Obesity").heal();
diseases.get("Perfectionism").heal();
diseases.get("Agoraphobia").heal();
}
@Override
public void goOut() {
house.getPC().shutDown();
wife.argue();
}
@Override
public void doSports() {
goOut();
BigWideWorld.getGym("McFit").visit();
}
@Override
public void meetFriends() {
goOut();
BigWideWorld.searchFriend().meet();
}
}
Ich weiß, das ist eine sehr alte Frage mit vielen guten Antworten. Ich möchte nur auf die einfachste (zumindest für mich einfachste) Weise hinweisen, diesen Operator zu verstehen.
Wenn o instanceof t
true
zurückgibt, wirft ___t castedObj = (t) o;
keine ClassCastException
und castedObj
wird keine null
sein.
Dies ist wichtig/nützlich, wenn Sie später auf Felder oder Methoden von castedObj
zugreifen möchten - Sie wissen, dass Sie durch die instanceof
-Prüfung später keine Probleme mehr haben werden.
Der einzige Nachteil ist, dass dies für Typen ohne Generics verwendet werden kann.