简体   繁体   中英

How to proper generify a method which returns an instance using Reflection API?

I want to retrive an instance by Class type. But for now I struggling with generics. My code doesn't work and I don't know actually why. Here it is:

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());
    }
}

Provider class with broken create method

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);
    }
}

Here is my Holder impl.

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

And AbstractHolder abstract class.

public abstract class AbstractHolder {
    private String property;

    public AbstractHolder(String property) {
        this.property = property;
    }

    public String getProperty() {
        return property;
    }
}

Any ideas how can I fix generics in my Provider class?

PS

The problem is in this method

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

Try this:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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