This is my problem
public class Row{
//It is just a class
}
public class RowUsedByThisClass{
public Row someOp(Row r){
/*I am Using this method with r a instance of Row.
*r may be sub type of the Row. I have to inspect r and have to
*return a new instance. But the new instance just cant be type
*Row it should be exact subtype r belongs.In shor i have to
*开发者_如何转开发determin the type of return object runtime.
*Is it possible in java? Can i use generics.
*/
}
}
If you have a no-arg constructor for each subclass of Row
, then inside someOp
you can use r.getClass().newInstance()
.
This requires reflection, not generics:
Row newRow = r.getClass().newInstance();
However, this reqires the class to have a default (parameterless) constructor.
I think you're supposed to implement someOp()
for each subclass of Row
.
Then you are essentially using method dispatch as your mechanism for detecting the class and can handle the op appropriately for each class.
You can use the getClass() function to determine the type of the object.
Actually you have 2 ways to determine the object type.
First is using keyword instanceof:
if (row instanceof MyRow) {
// do something
}
Second is using getClass():
Class clazz = row.getClass();
if (clazz.equals(MyRow.class)) {}
if (MyRow.calss.isAssignableFrom(clazz)) {}
Then you can decide what you want. For example you can even create new instance of other class that extends Row and return it or wrap row passed using argument.
You can and should specify that in the type signature:
public class RowUsedByThisClass <T extends Row> {
public T someOp (T t) {
You can use the reflection API and a little bit of generics to achieve what you want.
import java.lang.reflect.Constructor;
class Row {
//It is just a class
}
class RowUsedByThisClass {
public <R extends Row> R someOp(final R r) {
R newR = null;
try {
// Use no-args constructor
newR = (R) r.getClass().newInstance();
// Or you can use some specific constructor, e.g. in this case that accepts an Integer, String argument
Constructor c = r.getClass().getConstructor(Integer.class, String.class);
newR = (R) c.newInstance(1, "2");
// do whatever else you want
} catch (final Exception ex) {
// TODO Handle this: Error in initializing/cconstructor not visible/...
}
return newR;
}
}
精彩评论