简体   繁体   English

通过使用反射方法在抽象类中创建具体对象

[英]Create a concrete object in a abstract class by using reflect methods

Suppose I have an abstract class called Model with the following static method: 假设我有一个名为Model的抽象类,具有以下静态方法:

public abstract class Model {
    ...
    public static List<Model> all() {
       ...
    }
    ...
}

And a concrete class the extends it: 一个具体的类对其进行了扩展:

public class Person exends Model {
...
}

So, is it possible to, using a static context, Person.all() return a list of Person and not of Model ? 因此,是否有可能使用静态上下文, Person.all()返回Person列表而不是Model列表?

You know, by using a Template, or reflect methods such as getClass().getClassName() and getClass().getDeclaredMethod() and etc. 您知道,通过使用模板或反映诸如getClass().getClassName()getClass().getDeclaredMethod()等方法。

I am asking that because I have seen that in a PHP library and I am creating a similar library in java. 我之所以这么问是因为我已经在PHP库中看到了这一点,并且正在用Java创建类似的库。

You should always avoid reflection whenever possible. 您应尽可能避免反射。 It's slow, it's hard to debug, it bypasses compile-time checking of types and signatures, and it can't be optimized at runtime by the JIT. 它速度慢,难以调试,绕过类型和签名的编译时检查,并且JIT无法在运行时对其进行优化。

You probably want to use a Supplier instead: 您可能想改用供应商:

public static <M extends Model> List<M> all(Supplier<M> constructor) {
    List<M> models = new ArrayList<>();

    for ( /* ... */ ) {
        M model = constructor.get();

        // initialize model here
        // ...

        models.add(model);
    }
}

An invocation of the method looks like this: 该方法的调用如下所示:

List<Person> allPersons = all(Person::new);

Assuming, of course, that the Person class has a zero-argument constructor, or defines no constructor at all. 当然,假设Person类具有零参数构造函数,或者根本没有定义构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM