简体   繁体   中英

How can i load an implementation of an interface at runtime and call the methods of said class?

Trying to use extcos to dynamically link my interface implementation at runtime so users could make their own class, compile it and use my program. Im having problems extracting the class though. Working with classes like this is way over my head, but looks like extcos does most of the work.

I try to load the class right as my program enters main. Here is what i have in there atm:

    final Set<Class<? extends IAlgorithm>> classes = new HashSet<Class<? extends IAlgorithm>>();

    ComponentScanner scanner = new ComponentScanner();
    scanner.getClasses(new ComponentQuery() {
        @Override
        protected void query() {
            select().
            from("logic").
            andStore(thoseImplementing(IAlgorithm.class).into(classes)).
            returning(none());
        }
    });

How do i get the instance to call my methods in the implementation of IAlgorithm?

http://sourceforge.net/projects/extcos/

I don't know extcos, but it sure looks like classes contains the java.lang.Class<?> objects for your loaded classes. You should be able to create instances of those classes with

IAlgorithm ia = classes.iterator().next().newInstance();

for the no-arg-constructor case; or if you need to invoke a non-default constructor:

Class<? extends IAlgorithm> cls = classes.iterator().next();
Constructor<? extends IAlgorithm> c = cls.getConstructor(...);
IAlgorithm ia = c.newInstance(...);

where ... represents the constructor argument types and values respectively in the first and second usages above.

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