Skip to content

corneil/static-requirements

Repository files navigation

Static Requirements

Introduction

Oliver Gierke tweeted

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.

Example

Template Class

public class StaticTemplate {
    public static InterfaceRequiresStatic create(String arg) {
        throw new NoSuchMethodError("create");
    }
}

Interface

@RequiresStatic(StaticTemplate.class)
public interface InterfaceRequiresStatic {
    String someMethod();
    void otherMethod(String arg);
}

Implementation

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;
    }    
}

Performing Check

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.
}

Sample Code

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.

Use

If anyone is interested in using this let me know by logging an issue or tweeting to me at @corneil

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages