关于Java反射的几个问题



我有父类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();
}

我不确定这在你的情况下是否有用,但这是唯一的方法,如果你想要静态

使用泛型:

// Subclasses will have to pass their type as a generic type argument
// Which you will use to declare the return type of get()
class Entity<T extends Entity<T>> {
    T get(int id) {
        T value = ...; // Load the value from db or whatever
        return value;
    }
}
// Child tells its parent that the dynamic type is Child
class Child extends Entity<Child> {
}

相关内容

  • 没有找到相关文章

最新更新