关于Java Reflection的一些问题

时间:2014-08-18 09:17:50

标签: java inheritance reflection

我有父类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的实例?如何在父类中指定子类[es]的结果类型?

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

2 个答案:

答案 0 :(得分:3)

由于类型擦除,无法在运行时获取静态上下文中的实际类型。在调用方法时,您必须显式声明该类。使用通用方法,它看起来像这样:

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

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

答案 1 :(得分:1)

使用泛型:

// 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> {

}