Square peg, meet round hole...
February 21, 2010 2:28 PM Subscribe
Java gurus: How write a type cast that specifies both a superclass and an interface?
I have something like this going on:
void f(Object o) {
g(o);
}
<T extends MySuperClass & MyInterface> void g(T x) {
...;
}
How can I cast o so that this works? There seems to be no way to specify both a base class and an interface in variable declarations without using generics. I don't think generics will work here, because o is being created dynamically using reflection, so its actual class is not known at compile time. Please hope me!
I have something like this going on:
void f(Object o) {
g(o);
}
<T extends MySuperClass & MyInterface> void g(T x) {
...;
}
How can I cast o so that this works? There seems to be no way to specify both a base class and an interface in variable declarations without using generics. I don't think generics will work here, because o is being created dynamically using reflection, so its actual class is not known at compile time. Please hope me!
Response by poster: Good point. I've now posted it on StackOverflow, and here's the answer for the curious:
void f(Object o) {
Caster<> c = new Caster();
g(c.cast(o));
}
class Caster {
public T cast(Object o) {
return (T) o;
}
} >
Case closed.
posted by qxntpqbbbqxl at 5:39 PM on February 21, 2010
void f(Object o) {
Caster<> c = new Caster();
g(c.cast(o));
}
class Caster
public T cast(Object o) {
return (T) o;
}
}
Case closed.
posted by qxntpqbbbqxl at 5:39 PM on February 21, 2010
Response by poster: Oops, forgot to quote the html entities. Let's try again.
void f(Object o) {
Caster<?> c = new Caster();
g(c.cast(o));
}
class Caster<T extends MySuperClass & MyInterface> {
public T cast(Object o) {
return (T) o;
}
}
posted by qxntpqbbbqxl at 5:42 PM on February 21, 2010
void f(Object o) {
Caster<?> c = new Caster();
g(c.cast(o));
}
class Caster<T extends MySuperClass & MyInterface> {
public T cast(Object o) {
return (T) o;
}
}
posted by qxntpqbbbqxl at 5:42 PM on February 21, 2010
This thread is closed to new comments.
You might have better luck with sort of question on StackOverflow
posted by miasma at 2:41 PM on February 21, 2010 [2 favorites]