如何在运行时更改新实例的类型

3

这是我的问题。

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.
    */
  }

}

@Ted:抱歉我覆盖了你的编辑。我已经将它恢复到你的版本了。 - Adam Paynter
@Adam:别担心,这很容易犯错。 - Ted Hopp
7个回答

2

如果每个Row子类都有一个无参构造函数,在someOp内部,您可以使用r.getClass().newInstance()


1

这需要反射,而不是泛型:

Row newRow = r.getClass().newInstance();

然而,这需要类具有默认(无参数)构造函数。


1

我认为你应该为Row的每个子类实现someOp()

然后,您基本上使用方法分派作为检测类的机制,并且可以适当地处理每个类的操作。


1
委托位加1。但是问题在于现在每个子类都必须覆盖该方法并记得返回其自身类型的实例。 - shams

0

实际上,您有两种方法来确定对象类型。

第一种是使用关键字instanceof:

if (row instanceof MyRow) {
    // do something
}

第二种方法是使用getClass():

Class clazz = row.getClass();
if (clazz.equals(MyRow.class)) {}
if (MyRow.calss.isAssignableFrom(clazz)) {}

然后你可以决定你想要什么。例如,您甚至可以创建扩展Row的其他类的新实例并返回它,或者使用参数传递的行进行包装。

0

你可以并且应该在类型签名中指定:

public class RowUsedByThisClass <T extends Row> {
  public T someOp (T t) {

0

您可以使用反射 API和一些泛型来实现您想要的功能。

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;
    }
}

0
您可以使用getClass()函数来确定对象的类型。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接