I'm currently developing a framework where I'll provide an Interface that the user should implement in his application for configuration purposes. The user should ne able to implement a getTargetUsername()
that will be used in the framework side.
What I'm trying to achieve a is pretty much what Togglez do:
public class MyTogglzConfiguration implements TogglzConfig {
public Class<? extends Feature> getFeatureClass() {
return MyFeatures.class;
}
}
My problem is that I'm struggling to find how should I lookup for the class that is implementing my configuration interface. And call the getTargetUsername()
method inside the framework.
I'm currently trying to do the trick using Reflections
, but I'm not sure this is the right approach, since I don't know if this is looking only inside my framework package or it will search inside a prject that add it as a dependency.
Reflections reflections = new Reflections();
Set<Class<? extends FrameworkConfig>> configurations = reflections.getSubTypesOf(FrameworkConfig.class);
//Getting the Class thats is implementing here
Object c = configurations.toArray()[0];
I'm being able to get the right Class with the above code but I acctually can't call getTargetUsername()
.
If your configurations
set already contains all relevant classes, then the first step is to create a new instace of that class.
Class<? extends FrameworkConfig> clazz = configurations.iterator().next();
FrameworkConfig myInstance = clazz.newInstance();
After that you can call the method as usual:
Class<? extends Feature> featureClass = myInstance.getFeatureClass();
After that you can do whatever you want with that information. But I assume, that you will create a new instance of that class also:
Feature myFeature = featureClass.newInstance();
Now you can interact with that instance:
myFeature.foo();
All this code assumes, that bot classes FrameworkConfig
and Feature
have a default constructor - a public constructor without parameters.