Wishing there was a way to specify in an interface that the implementation must have certain static factory methods.
This is an implementation using Annotation Processor to provide a solution.
public class StaticTemplate {
public static InterfaceRequiresStatic create(String arg) {
throw new NoSuchMethodError("create");
}
}
@RequiresStatic(StaticTemplate.class)
public interface InterfaceRequiresStatic {
String someMethod();
void otherMethod(String arg);
}
public class MyClass implements InterfaceRequiresStatic {
@Override
public String someMethod() {
return null;
}
@Override
public void otherMethod(String arg) {
}
public static InterfaceRequiresStatic create(String arg) {
InterfaceRequiresStatic result = new MyClass();
result.otherMethod(arg);
return result;
}
}
Annotations on interfaces are not inherited. With the Annotation Processor there is a chance of missing a case.
It is advisable to use RequiresStaticSupport
to perform the check.
if(RequiresStaticSupport.checkClass(MyClass.class)) {
// use as needed.
// an exception will be thrown if the requirement isn't met.
}
If you want to execute the samples:
The following will build the core.
./gradlew :core:build
The following will compile the tests and should fail.
./gradlew :tests:build
Edit core/src/main/resources/META-INF/services/javax.annotation.processing.Processor
and comment the annotation processor to ensure compilation.
If anyone is interested in using this let me know by logging an issue or tweeting to me at @corneil