Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 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 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...