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!
posted by qxntpqbbbqxl to Computers & Internet (3 answers total)
 
Best answer: Write to the interface, not the implementation. Basically, if in the g() method you need a T, then use a T... it seems extremely rare that you would need it to comply with multiple interfaces. Otherwise, use the interface that comes with the SuperClass, but it seems really strange to need to use both at once.

You might have better luck with sort of question on StackOverflow
posted by miasma at 2:41 PM on February 21, 2010 [2 favorites]


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


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


« Older Looking for Accom in UK   |   What's between Denver and Austin? Newer »
This thread is closed to new comments.