Java 使用「;instanceof";在爪哇

Java 使用「;instanceof";在爪哇,java,operators,instanceof,Java,Operators,Instanceof,我了解到Java有instanceof操作符。你能详细说明一下它的用途和优点吗?instanceof是一个关键字,可以用来测试对象是否属于指定类型 例如: public class MainClass { public static void main(String[] a) { String s = "Hello"; int i = 0; String g; if (s instanceof java.lang.String) { //

我了解到Java有
instanceof
操作符。你能详细说明一下它的用途和优点吗?

instanceof是一个关键字,可以用来测试对象是否属于指定类型

例如:

public class MainClass {
    public static void main(String[] a) {

    String s = "Hello";
    int i = 0;
    String g;
    if (s instanceof java.lang.String) {
       // This is going to be printed
       System.out.println("s is a String");
    }
    if (i instanceof Integer) {
       // This is going to be printed as autoboxing will happen (int -> Integer)
       System.out.println("i is an Integer");
    }
    if (g instanceof java.lang.String) {
       // This case is not going to happen because g is not initialized and
       // therefore is null and instanceof returns false for null. 
       System.out.println("g is a String");
    } 
} 

这是我的。

instanceof
用于检查对象是类的实例、子类的实例还是实现特定接口的类的实例


基本上,检查对象是否是特定类的实例。 当您有一个超类或接口类型的对象的引用或参数,并且需要知道实际对象是否有其他类型(通常更具体)时,通常会使用它

例如:

public void doSomething(Number param) {
  if( param instanceof Double) {
    System.out.println("param is a Double");
  }
  else if( param instanceof Integer) {
    System.out.println("param is an Integer");
  }

  if( param instanceof Comparable) {
    //subclasses of Number like Double etc. implement Comparable
    //other subclasses might not -> you could pass Number instances that don't implement that interface
    System.out.println("param is comparable"); 
  }
}

请注意,如果必须经常使用该运算符,则通常暗示您的设计存在一些缺陷。因此,在设计良好的应用程序中,您应该尽可能少地使用该运算符(当然,该一般规则也有例外)。

instanceof
可用于确定对象的实际类型:

class A { }  
class C extends A { } 
class D extends A { } 

public static void testInstance(){
    A c = new C();
    A d = new D();
    Assert.assertTrue(c instanceof A && d instanceof A);
    Assert.assertTrue(c instanceof C && d instanceof D);
    Assert.assertFalse(c instanceof D);
    Assert.assertFalse(d instanceof C);
}

你有没有看过这个链接,所以应该给你很多想法:如果我用谷歌搜索你的问题,我会得到1170万个结果。有什么你想知道的东西还没有被详细讨论过吗?Dup也许,但像这样的问题在所有技能水平上都是一个很好的资源。我很高兴这是我搜索时得到的最好的结果。这里有一篇关于这个用法的好文章:
Integer.class
格式真的合法吗?在Eclipse中,当我尝试在您的示例中使用它时,我在标记“class”上得到了
语法错误,标识符应为
。不过,将其切换为简单的
Integer
效果很好。@如果你是对的,我会解决这个问题。我已经有一段时间没有写那个答案了;)找到此方法的常见位置是
.equals()
方法。intelliJ通常会生成使用
instanceof
的equals方法,只是想添加为什么使用此运算符表示设计缺陷。需要转换为具体类型的抽象没有提供足够的信息。要么是一些糟糕的抽象,要么是在错误的领域中使用的抽象。您可以通过以下示例查看详细说明:。使用instanceof运算符时,请记住null不是任何对象的实例。如果
,为什么不使用
?现在,第二个和第三个条件没有被评估,因为第一个条件是
true
@HummelingEngineeringBV实际上你是对的,我对蒂姆的评论反应有点太快了。我们确实希望评估每一种情况。谢谢你,编辑。在你的设计中肯定会有使用instanceof的情况,特别是在开发API和抛出误用异常的情况下。我喜欢这个答案,但我正在创建一个lexer,我需要使用
instanceof
来确定令牌的类型(例如,
标识符
文字
等,从
标记扩展而来)。如果我不打算使用
instanceof
,那么我将拥有一个唯一的
令牌
类,并且必须创建各种不必要的不同类型的字段来保存实际令牌的值。未命中引导答案,这需要一种情况并对整个关键字进行判断=\@Hydro您还可以引入一个专用的\texttt{enum}类,用于您的令牌类型。