如何使用反射API正确地泛化返回实例的方法



我想按class类型检索实例。但现在我在仿制药上挣扎。我的代码不工作了,我也不知道为什么。

public class Main {
    public static void main(String[] args) throws Exception {
        Provider provider = new Provider("prop");
        AbstractHolder obj = provider.create(DefaultHolder.class);
        System.out.println(obj.getProperty());
    }
}

带有破碎create方法的提供商类

public class Provider {
    private String property;
    public Provider(String property) {
        this.property = property;
    }
    public <T> create (Class<T> type) throws Exception {
        return type.getConstructor(String.class).newInstance(property);
    }
}

这是我的Holder impl。

public class DefaultHolder extends AbstractHolder {
    public DefaultHolder(String field) {
        super(field);
    }
}

和abstracholder抽象类。

public abstract class AbstractHolder {
    private String property;
    public AbstractHolder(String property) {
        this.property = property;
    }
    public String getProperty() {
        return property;
    }
}

任何想法我怎么能在我的提供者类修复泛型?

p>

题出在这个方法上
public <T> create (Class<T> type) throws Exception {
    return type.getConstructor(String.class).newInstance(property);
}

试试这个:

public class Main {
    public static void main(String[] args) throws Exception {
        Provider provider = new Provider("prop");
        AbstractHolder obj = provider.create(DefaultHolder.class);
        System.out.println(obj.getProperty());
    }
}
public class Provider {
    private String property;
    public Provider(String property) {
        this.property = property;
    }
    public <T extends AbstractHolder> T create(Class<T> type) throws InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {
        return type.getConstructor(property.getClass()).newInstance(property);
    }
}

相关内容

  • 没有找到相关文章

最新更新