IAmYourFaja
IAmYourFaja

Reputation: 56914

Abstracting Java Annotations

I have a particular situation where I would like to create an annotation that can accept a "base" annotation as one of its parameters:

public @interface Fleet
{
    int fleetSize();
    Vehicle fleetType();
}

Where @Vehicle is a "base" annotation for different types of vehicles that will accept different parameters that make sense for them:

public @interface Vehicle {}

public @interface Car extends Vehicle {
    boolean is2WheelDrive();
}

public @interface Motorcycle extends Vehicle {
    String manufacturer();
}

So that the @Fleet annotation can be used like so:

// A fleet of 20 Hyabusas
@Fleet(20, @Motorcycle("Hyabusas"))
public void doSomething() {
    // ...
}

// A fleet of 5 4-Wheel-drive cars
@Fleet(5, @Car(false))
public void doSomethingElse() {
    // ...
}

Now, first off, a few things: yes I know this example illustrates a terrible design! And I know that you can't extend an annotation with Java.

Given those two known evils, how could I refactor those code snippets anyways so that the following constraints are met:

Thanks in advance!

Upvotes: 3

Views: 118

Answers (1)

Tom Anderson
Tom Anderson

Reputation: 47183

I don't think you can really do this.

The normal approach would be to apply both @Fleet and one of @Car and @Motorcycle to the class. Not ideal, admittedly.

Upvotes: 1

Related Questions