我有父类Entity

package incubator;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class Entity {

    private String getTableName() {
        String result = null;
        Class<?> cl = getClass();
        System.out.println(cl.getName());
        for (Annotation a : cl.getAnnotations()) {
            if (a instanceof EntityTable) {
                EntityTable ent = (EntityTable) a;
                result = ent.name();
                break;
            }
        }
        return result;
    }

    private String getKeyName() {
        String result = null;
        Class<?> cl = getClass();
        System.out.println(cl.getName());
        for (Field f : cl.getDeclaredFields()) {
            for (Annotation a : f.getAnnotations()) {
                if (a instanceof PrimaryKey) {
                    PrimaryKey ann = (PrimaryKey) a;
                    result = ann.name();
                }
            }
        }
        return result;
    }

    public Entity get(int id) throws IllegalAccessException, InstantiationException {
            System.out.println("SELECT * FROM "
                    + getTableName() + " WHERE (" + getKeyName() + "=?);");
            return getClass().newInstance();
    }

    public void delete() {
            System.out.println("DELETE FROM "
                    + getTableName() + " WHERE (" + getKeyName() + "=?);");
    }

}


和子类Child

package incubator;

@EntityTable(name="table")
public class Child extends Entity {
  @PrimaryKey(name="tbl_pcode")
  private int id;
  @DataField(name="tbl_text")
  public String text;
  @DataField(name = "tbl_data")
  public String data;

  public Child() {
      id = 0;
  }
}


所有注释都像

package incubator;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EntityTable {
    String name();
}


因此,我有一个问题:有什么办法可以使类get(final int id)的静态方法Entity返回Child的实例?如何在父类中指定子类的结果类型?

感谢您浪费我的时间。最好的祝福。

最佳答案

由于类型擦除,无法在运行时在静态上下文中获取实际类型。调用该方法时,您必须显式声明该类。使用通用方法将如下所示:

public static <T extends Entity> T get(int id, Class<T> clazz) {
    return clazz.newInstance();
}


我不确定这是否对您有用,但这是您保持静态的唯一方法。

10-01 00:14