instanceof
può essere utilizzato per verificare se un oggetto è un'istanza diretta o discendente di una determinata classe. instanceof
può anche essere utilizzato con le interfacce anche se le interfacce non possono essere istanziate come le classi. Qualcuno può spiegare come funziona instanceof
?Come instanceof funzionerà su un'interfaccia
risposta
Prima di tutto, siamo in grado di memorizzare instances
di classi che implementa un particolare interface
in un interface reference variable
come questo.
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 {
}
Per esempio, qualsiasi istanza runtime che implementa una particolare interfaccia passerà il test instanceof
EDIT
e l'uscita
instanceof succeeded
instanceof succeeded
@RohitJain
È possibile creare istanze di interfacce utilizzando le classi interne anonime come questo
Runnable runnable = new Runnable() {
public void run() {
System.out.println("inside run");
}
};
e si prova l'istanza è di tipo di interfaccia, utilizzando instanceof
operatore come questo
System.out.println(runnable instanceof Runnable);
e il risultato è 'vero'
object instanceof object_interface
produrrà true
.
L'operatore instanceof ti dirà se il primo argomento è un oggetto che implementa il secondo argomento. Non capisco perché sia importante che tu non possa creare direttamente un'istanza dell'interfaccia.
Integer num = 1;
if (num instanceof Number) {
System.out.println("An integer is a number!");
}
Questo è tutto ciò che serve.
Nell'esempio manca il punto della domanda - 'Numero intero _estende_ (non implementazioni)' Numero'. –
si fa un controllo di un instanceof
reference
contro un instance
, e controlla il tipo di instance
quel particolare reference
sta indicando.
Ora, poiché è possibile creare un riferimento di un interface
, che punta a un'istanza di attuazione class
(stesso concetto, Super class reference
punta a subclass instance
). Quindi, puoi fare un controllo su instanceof
.
Per es: -
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.
}
}
Cosa? Ovviamente '(obj instanceof ImplClass) == true', classe obj IS ImplClass! La domanda è, '(obj instanceof MyInterface) == true'? Immagino sia un errore di battitura. La spiegazione è un po 'confusa tra di loro. –
- Prima di tutto instanceof viene utilizzato per confrontare se la variabile di riferimento oggetto che contiene l'oggetto è di tipo determinato o no.
Es:
public void getObj(Animal a){ // a is an Object Reference Variable of type Animal
if(a instanceof Dog){
}
}
- Nel caso interface
, il class
che attua può essere usato con instanceof
.
Esempio:
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 Il sotto si produrrà True per l'instanceof:
• 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
favore, vai a questo link per avere un'idea chiara:
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();
}
}
Bella arte ascii! – winklerrr
So che questa è una domanda molto vecchia con molte buone risposte. Voglio solo indicare il modo più semplice (almeno per me è più facile) per capire questo operatore.
If o instanceof t
rendimenti true
, poi t castedObj = (t) o;
non gettare ClassCastException
, e castedObj
non saranno null
.
Questo è importante/utile se si desidera accedere a campi o metodi da castedObj
in seguito - si sa che eseguendo il controllo instanceof
, non si avranno più problemi in seguito.
L'unico svantaggio è che questo può essere utilizzato per tipi senza generici.
Probabilmente intendevi 'instanceof Test' nelle tue condizioni if. –
no .. la domanda riguardava l'uso di 'instanceof' contro' interface'. rt? – sunil
@sunil .. Sì, è vero. Ma se controlli un 'instanceof' con un'interfaccia, otterrai sempre risultati falsi. Poiché non è possibile creare un'istanza di un'interfaccia, non è significativo verificare se un riferimento punta a un'istanza di essa. Spero che tu abbia quello che voglio dire. –