Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Class have a nice generic type in this case?

Tags:

java

In this code, why can type not be declared as Class<? extends B>?

public class Foo<B> {
    public void doSomething(B argument) {
        Class<? extends Object> type = argument.getClass();
    }
}
like image 299
Ed Thomas Avatar asked Dec 06 '12 08:12

Ed Thomas


1 Answers

This problem is that Java's syntax doesn't allow getClass() to say it's returning a type which matches the class its defined in, and this is not a special case as far as the compiler is concerned. So you are forced to cast the result.

There are many cases where you would like to be able to specify this type, e.g. for chaining, so I would hope they include this feature one day.

You could write

Class<? extends this> getClass();

or

public this clone(); // must return a type of this class.

or

class ByteBuffer {
    this order(ByteOrder order);
}

class MappedByteBuffer extends ByteBuffer {
}

// currently this won't work as ByteBuffer defines order()
MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, fc.size())
                         .order(ByteOrder.nativeOrder());
like image 131
Peter Lawrey Avatar answered Oct 09 '22 12:10

Peter Lawrey