Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • The @Fleet annotation can be passed either a @Car or @Motorcycle
  • @Car and @Motorcycle accept different (both in quantity and type) arguments

Thanks in advance!

like image 516
IAmYourFaja Avatar asked Jan 19 '26 23:01

IAmYourFaja


1 Answers

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.

like image 146
Tom Anderson Avatar answered Jan 21 '26 12:01

Tom Anderson