I
Ian Pilcher
This compiles:
class Foo
{
boolean foo(Object o)
{
class Local
{
public boolean equals(Object o)
{
return o != null && (o instanceof Local);
}
}
Local local = new Local();
return local.equals(o);
}
}
This doesn't:
class Foo<T>
{
boolean foo(Object o)
{
class Local
{
public boolean equals(Object o)
{
return o != null && (o instanceof Local); // ******
}
}
Local local = new Local();
return local.equals(o);
}
}
javac complains that the marked line contains an "illegal generic type
for instanceof". I've encountered similar problems before with inner
classes:
class Foo<T>
{
class Bar {}
boolean isBar(Object o)
{
return o != null && (o instanceof Bar);
}
}
javac will issue the same cryptic error message. What it's failing to
communicate is that an inner class of a parameterized type is itself
implicitly parameterized. So "o instanceof Bar" really means
"o instanceof Foo<T>.Bar".
In this case, the workaround is pretty obvious. "o instanceof Foo.Bar"
works. The Eclipse compiler calls this the "raw form".
So what's the raw form of a Local class name? AFAIK, that's up to the
compiler. javac generates names like Foo$1Local, and it is in fact
possible to use this name -- "o instanceof Foo$1Local". Talk about a
recipe for brittle code!
Is there a solution I'm missing -- other than calling
getClass().instanceOf(o)?
class Foo
{
boolean foo(Object o)
{
class Local
{
public boolean equals(Object o)
{
return o != null && (o instanceof Local);
}
}
Local local = new Local();
return local.equals(o);
}
}
This doesn't:
class Foo<T>
{
boolean foo(Object o)
{
class Local
{
public boolean equals(Object o)
{
return o != null && (o instanceof Local); // ******
}
}
Local local = new Local();
return local.equals(o);
}
}
javac complains that the marked line contains an "illegal generic type
for instanceof". I've encountered similar problems before with inner
classes:
class Foo<T>
{
class Bar {}
boolean isBar(Object o)
{
return o != null && (o instanceof Bar);
}
}
javac will issue the same cryptic error message. What it's failing to
communicate is that an inner class of a parameterized type is itself
implicitly parameterized. So "o instanceof Bar" really means
"o instanceof Foo<T>.Bar".
In this case, the workaround is pretty obvious. "o instanceof Foo.Bar"
works. The Eclipse compiler calls this the "raw form".
So what's the raw form of a Local class name? AFAIK, that's up to the
compiler. javac generates names like Foo$1Local, and it is in fact
possible to use this name -- "o instanceof Foo$1Local". Talk about a
recipe for brittle code!
Is there a solution I'm missing -- other than calling
getClass().instanceOf(o)?