Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

java - Return reference to class from reflections to call constructor in factory

In my project, I have a java package that contains simple converter objects. These objects have one function: 'Convert'. This function will convert a parameter to another format.

As soon as I add another class to the map I will give the class an annotation so I can find the class with reflections.

Now I see that sometimes the class needs an additional parameter for example when I'm having a split converter. I think the best way to do this is by setting the parameter in the constructor as soon as I call the class.

What I am doing right now is as soon as reflection sees the converter it will automatically create a new instance of the class.

    public static Map<String, IConverter> getConverterMappings() {
    Reflections reflections = new Reflections("prefix.domainname.project.utils.converters");
    Set<Class<?>> converterClasses = reflections.getTypesAnnotatedWith(Converter.class);

    return converterClasses.stream()
            .collect(Collectors.toMap(
                    converterClass -> converterClass.getAnnotation(Converter.class).name(),
                    ConverterFinderImpl::createNewInstanceOfClass
            ));
}

private static <T> IConverter createNewInstanceOfClass(Class<T> someClass) {
    try {
        return (IConverter) someClass.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

As you can see it returns a mapping with a string and a converter class. The string will be used later on to find the corresponding converter. What I need is to get a reference to the class and not the class itself so I can call it in a factory.

question from:https://stackoverflow.com/questions/65626173/return-reference-to-class-from-reflections-to-call-constructor-in-factory

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...