See the bottom for the solution.
I’m trying to write some generic handling code, but in 1 of the sub-classes, it requires a Class that is more specific.
So the base class as a field of type Class, and in the subclass I’m trying to cast that Class object to type Class which is a subclass of org.apache.hadoop.hbase.mapreduce.Mapper.
I get the following error from Netbeans:
"Incompatible types
required: java.lang.Class<org.apache.hadoop.hbase.mapreduce.TableMapper>
found: java.lang.class<capture#3 of ? extends org.apache.hadoop.mapreduce.Mapper>"
when I try the following code
Class<TableMapper> tableMapperClass = null;
if( mapperClass.equals(TableMapper.class) ) {
tableMapperClass = TableMapper.class.asSubclass(mapperClass);
//do stuff
}
and I get:
incompatible types
required: java.lang.Class<org.apache.hadoop.hbase.mapreduce.TableMapper>
found: java.lang.Class<capture#8 of ? extends org.apache.hadoop.hbase.mapreduce.TableMapper>
for
Class<TableMapper> tableMapperClass = null;
if( mapperClass.equals(TableMapper.class) ) {
tableMapperClass = mapperClass.asSubclass(TableMapper.class);
//do stuff
}
Ok, got the answer from my co-worker, looks like this should work:
Class<? extends TableMapper> tableMapperClass = null;
if( mapperClass.equals(TableMapper.class) ) {
tableMapperClass = mapperClass.asSubclass(TableMapper.class);
//do stuff
}
If you want to assign a class to tableMapperClass that is actually a subclass of TableMapper, then you need to change the type of the variable. Instead, use:
and now you can assign TableMapper.class or any subclass to this variable. When you write
Class<TableMapper>you are promising that the variable will be exactly TableMapper.class or null.Another example:
Note that you can do different things with
Class<Number>then you can withClass<? extends Number>. For example, you can call a constructor ofClass<Number>, because you know the class. You can’t do that withClass<? extends Number>because the constructors are not defined at compile time.Similarly with, say,
List<Number>vsList<? extends Number>. You can call list.add(7) on a variable of typeList<Number>, but you can’t do that on aList<? extends Number>because you don’t know the type of the second list. It might be aList<Double>for example, in which case adding an Integer is not allowed.Generics are weird. 🙂 Hope this helps.