Invoke Method of Subclass with Matching Regex - java

I am trying to call a method, convert(), based upon the return value matching the class' regex() method, both of which are defined in the below base class:
public abstract class BaseClass {
public abstract BaseClass convert(String value);
public abstract String regex();
}
I also have several subclasses that have implementations of those methods. I want to be able to do something like the below method (which will reside in BaseClass):
public static BaseClass parseNew (String value) {
// I use a switch statement to convey the idea of what I want to
// do, not for functionallity. Any non-constant cases raise
// compiler errors.
switch (value) {
case new Subclass1().regex():
return new Subclass1().convert(value);
case new Subclass1().regex():
return new Subclass1().convert(value);
// Repeat for all known and possibly unknown subclasses
}
}
I was thinking about using reflection, but I am very afluent in it. How would I get this functionality using reflection or some other concept?

The problem with this design is that it breaks abstraction (base aware of sub classes), making it a terrible idea.
A little about abstraction:
Abstraction is a process of hiding the implementation details from the user. Оnly the functionality will be provided to the user.
Instead you could make a different class which will contain this logic, and will act as a sort of factory.
Basically, you provide a base which exposes operations. This base is at the top of your inheritance tree. From it you provide implementations. The base in not aware of those implementations, they are not connected, they are specific. So the base class should know that sub exists, this just causes the code to be coupled and makes it non-modular and hard to maintain.
This mostly relates to creating a clean code.
So a quick look into factories... We want an object which will receive a value and parse it into an instance of BaseClass.
public class Parser {
private final Collection<BaseClass> implementations;
public Parser(Collection<BaseClass> implementations) {
this.implementations = implementations;
}
public BaseClass parseNew(String value) {
for (BaseClass implementation : implementations) {
if (implementation.regex().equals(value)) {
return implementation.convert(value);
}
}
throw new IllegalArgumentException("unsupported value");
}
}
The Parser class above is a factory which contains a collection of known BaseClass implementations. Using those, it may determine which implementation is wanted.
This is a pretty dynamic implementation. You would want to create an instance of this factory once, with the known implementations, and use it wherever.
General Design Note
There is also something weird about the the fact that BaseClass.convert returns BaseClass. I would expect it to return something else. BaseClass seems like a converter, and convert should return a value.
But that's just a general note.
Some reading resources:
https://www.geeksforgeeks.org/design-patterns-set-2-factory-method/
https://www.tutorialspoint.com/design_pattern/factory_pattern.htm
https://javatutorial.net/java-abstraction-example
http://www.javawithus.com/tutorial/relation-between-a-super-class-and-a-class

Related

Correct ways to enforce implementation of inherited static methods in Java?

My goal is to create an abstract class whose static methods have to be implemented, but I was having some issues due to static methods not being able to be made abstract.
This is the solution I came up with:
public abstract class CombinedMethod {
public static String computeMethodBody() throws
CannotCompileException {
throw new NotImplementedException();
}
public static ArrayList<CtMethod> sortSelectedMethods() {
throw new NotImplementedException();
}
}
I'm making this post because I couldn't find any equivalent answer, which left me wondering if this is idiomatic in Java.
Edit to add use case:
I want to create several classes that must all implement both computeMethodBody and sortSelectedMethods.
My solution adds structure and semantic meaning to the code, compared to, for example, creating documentation explaining how to create equivalent classes.
I am aware of why overriding static methods doesn't make sense in Java and that I'm just hiding them. As I said there's no other answer exemplifying this use case, but there's plenty discussing the concept.
Edit to add more details about the project:
The goal here is to implement some features of Common Lisp's method combination, using annotations as modifiers.
To name an example, suppose Class2 inherits from Class1:
public class Class1 {
...
#Combination("+")
public int myValue()
{
System.out.println("In myValue of Class1");
return 1;
}
}
public class Class2 extends Class1 {
...
#Combination("+")
public int myValue()
{
System.out.println("In myValue of Class2");
return 2;
}
}
Since they're both annotated with "+", I want to change the behaviour of this method at load time, so that Class2's effective method will be something behaviourally equivalent to:
#Combination("+")
public int myValue()
{
System.out.println("In myValue of Class2");
System.out.println("In myValue of Class1");
return 2 + 1;
}
To do so, I employed Javassist to compute a new effective method. Fortunately, I was able to generalize my architecture, so adding new functionality entails creating a static method and calling it inside a new switch case statement:
String computeEffectiveMethodBody(String annotationValue, CtClass ctClass, ArrayList<CtMethod> sortedSelectedMethods) throws CannotCompileException {
switch (annotationValue) {
case "min":
return CombinedMin.computeMethodBody(ctClass, sortedSelectedMethods);
case "max":
return CombinedMax.computeMethodBody(ctClass, sortedSelectedMethods);
case "+":
return CombinedAddition.computeMethodBody(ctClass, sortedSelectedMethods);
case "and":
return CombinedAnd.computeMethodBody(ctClass, sortedSelectedMethods);
case "or":
return CombinedOr.computeMethodBody(ctClass, sortedSelectedMethods);
default:
throw new RuntimeException("Invalid annotation");
}
}
The way I choose to segregate it was by creating a package called combinedMethods. Inside it, there's the parent function CombinedMethod and another subpackage called methods where all of the extensions with the actual static methods are kept.
Thank you #AasmundEldhuset for your interest, I'm always looking for the best way to architecture my software, even though I haven't learned it formally yet.
enforce implementation of inherited static methods in Java?
Java Language Specification says:
A class does not inherit private or static methods from its superinterface types.
Static methods are also called class methods. They are bound to a class and don't require an instance of the class in order to be invoked.
static and abstract is an illegal combination of modifiers because static methods are completely self-contained and always have an implementation.
You can not inherit static methods and as subsequence the concept of overriding is not applicable to them. And since a subclass can not override a parent's static method, abstract static method doesn't make sense because it can not be implemented.
A class method can be hidden by a method from a subclass with the same signature.
A quote from JLS:
A class (static) method that is hidden can be invoked by using a reference whose type is the type of the class that actually contains the declaration of the method. In this respect, hiding of static methods is different from overriding of instance methods.
I.e. hidden version can be invoked only on a child class or instance, conversely to the overridden method which can be invoked on the instance on of parent class or on the instance on of child class.
In other words, you can't obtain polymorphic behavior with static methods.
UPDATE
I want to create several classes that must all implement both computeMethodBody and sortSelectedMethods
So you want these two static methods with the same signature to be present in a couple of classes. And that's totally fine. But you don't need a parent abstract class for that because there's no useful code in it if both its method will be hidden.
creating documentation explaining how to create equivalent classes
Inheritance in Object-Oriented Programming isn't used for documentary purposes. The child should be capable to replace its parent in any use-cases, as Liskov substitution principle suggests.
The problem is that there are no use-cases for such a parent class. combinedMethod class isn't designed for inheritance (BTW, it's not a very informative name and by convention names of classes and interfaces should start with a capital letter).
You are misusing inheritance. If you need to provide the end-users of your classes with some additional information, there are other ways to do that:
The very first mean is a self-documenting code. Use clear, concise and self-explanatory names for your methods and classes.
Since Java 5 metadata can be provided with annotations.
In earlier versions, marker-interfaces were used for that purpose. But classes were never utilized for that.
Another thing that you need to understand is that although inheritance is a very important and useful mechanism, it also has pitfalls and should be applied after careful consideration.
Even if your case would be more suitable to apply inheritance, it wouldn't automatically mean that inheritance is the best option.
For instance, classes IntSummaryStatistics, LongSummaryStatistics and DoubleSummaryStatistics have no parent class in the JDK, although they have common fields and behavior.
Take a look at these classes a compare with your situation when parent isn't designed to be extended and has nothing to offer to its subclasses.
If you need to provide metadata - you can create a custom annotation like #CapableOfSomething and mark your classes with it, but don't abuse inheritance instead.
Static methods are invoked on a class, independent of an instance, so if they would be abstract, how would the run-time know on which sub-class to call them?
CombinedMethod cm1 = new SubclassA(...)
CombinedMethod cm2 = new SubclassB(...)
// static method computeMethodBody is called on neither cm1 or cm2, so what implementation to choose.
String result = CombinedMethod.computeMethodBody();

Java Relationship between interfaces/abstract classes

I am trying to build an algorithm that works in different ways depending on a traversal strategy and an update strategy. However, not every update Strategy works with every traversal strategy. Hence, I figured that an update strategy must only be instantiated with a corresponding traversal strategy. I wanted to force a constructor for that (see below). So that the subclasses would have to check if they support the strategy.
I am currently having an Interface
public interface TraversalStrategy {
...
}
And an (invalid) abstract class
public abstract class UpdateStrategy {
protected TraversalStrategy travStrategy;
public abstract UpdateStrategy(TraversalStrategy travStrategy);
}
What is the correct way to imply such a dependency? I could of course add an empty body to this constructor but that seemed wrong to me.
Update:
Inspired by the Answer of #Kayaman, I created a new class TestcaseGenerator that is used to construct a valid combination.
public TestcaseGenerator(TraversalStrategy travStrategy, UpdateStrategy updStrategy){
if (updStrategy.supports(travStrategy)){
this.travStrategy = travStrategy;
this.updStrategy = updStrategy;
}
}
What I don't like about this yet is, that it would now be unnecessary to give the instance of TraversalStrategy to the UpdateStrategy in order to check if it is supported. I would rather only need the class name. Can you tell me how to achieve that? Experiments with .getClass().getName() seemed horrible. Currently I am doing:
public boolean supports(TraversalStrategy travStrategy){
if(travStrategy instanceof UpstreamTraversalStrategy){
return true;
}
return false;
}
Even an abstract class must have a valid constructor. Even through it is not possible to create an instance of an abstract class, a non abstract subclass always calls the constructor of the super class first. Therefore your constructor on the abstract class needs a body to initialize the TraversalStrategy.
One common way is to have the superclass constructor call an abstract method such as isSupported(TraversalStrategy t); and fail if it's not true.
The subclasses would then implement the method accordingly by using instanceof or any other way to determine if the strategy is a supported one.
One approach would be to create a third class with a Builder pattern approach. Instead of providing TraversalStrategy as a parameter to UpdateStrategy, they would both be included in the third object (and they could be checked at build() to prevent incompatible strategies).
You could then have general functionality in the third class, with the strategy classes becoming lighter.

Possible design pattern instead of instanceof?

I am writing an object conversion class, used to convert domain layer objects into UI objects and vice versa. The problem is that my UI objects are organized into a hierarchy and as a result my object conversion class contains "instanceof" statements. There is a definite code smell here but I'm not sure what the solution is.
So my UI hierarchy contains a RuleDTO as follows:
public class RuleDTO {
protected long ruleID;
protected long rowID;
protected AttributeDTO leftCondition;
protected AttributeDTO rightCondition;
protected OperationTypeDTO operationType;
protected boolean isActive;
// etc...
}
My RuleDTO can then be subclassed by AssignmentRuleDTO as follows:
public class AssignmentRuleDTO extends RuleDTO {
protected String assignedToTeam;
protected String assignmentOperator;
// etc...
}
RuleDTO can also be subclassed by EvaluationRuleDTO:
public class EvaluationRuleDTO extends RuleDTO {
protected String successAction;
protected String failureAction;
// etc...
}
The problem is reached then in my ObjectConversionHelper class which contains the following type of logic:
{
// Perform logic common to RuleDTO such as setting ruleID, isActive etc
if(ruleDTO instanceof AssignmentRuleDTO) {
// Set assignedToTeam and assignmentOperator etc
}
else if (ruleDTO instanceOf EvaluationRuleDTO) {
// Set successAction and failureAction etc
}
}
What would be a good solution here instead? I've read about the visitor pattern, but not sure how it applies here.
Thanks
Your RuleDTO class should have a method called setStuff() or something similar.
Then you override it in AssignmentRuleDTO and in EvaluationRuleDTO to set the relevant fields.
This way your ObjectConversionHelper can just call
ruleDTO.setStuff();
I think using a Visitor pattern would be a reasonable approach here. So you'd have the Visitor interface
interface RuleDTO {
void visit(RuleDTO theRule);
void visit(EvaluationRuleDTO theEval);
void visit(AssignmentRuleDTO theAssign);
... and so on ...
}
And you'd add a method to these concrete classes to handle the double dispatch
public void accept(RuleDTOVisitor theVisitor) {
theVisitor.visit(this);
}
Lastly, you'd create some class which implements the visitor, say SettingPropertiesVisitor, and for each method, you can do the implementation where the appropriate fields for each object are set accordingly to your application requirements.
So then to use it
aRuleDTO.accept(new SettingPropertiesVisitor());
This way the appropriate visitor method will get invoked for each type, and then within the methods for your SettingPropertiesVisitor, you can do the appropriate assignments. This will get around the instanceof checks, and decouples that setter logic from the objects.
Of course, that might be overkill if this is the only visitor you ever create, in that case, instanceof isn't like killing kittens. But the obvious drawback here is each time you extend the API, you need to modify the visitor interface, and then probably all the concrete visitors to support the new method.
Visitor looks like overkill here IMHO.
There is no iteration over a graph of objects.
There is no requirement for double dispatch.
Remember KISS and YAGNI.
Just add an abstract method or leave it as-is.
You can always refactor later - assuming you have tests in place ;)
In your case, the visitor pattern could be applied by writing a convertToOtherClass method in RuleDTO, which is then overridden by its subclasses. You would then have, in your object conversion class, a method along the lines of convertRuleDTO (called in RuleDTO's convertToOtherClass method), which executes the relevant code, secure in the knowledge that it is operating on an instance of RuleDTO which has not been subclasses, because otherwise the subclass would override the convertToOtherClass method.
Take out the "else"... what's the problem?
There are a couple of plausible approaches. The two I would consider are using either an interface which all of your classes implement or using an enum that corresponds to your different classes.
If you have an interface (let's call it public interface DTO, you can have a method signature in it called setFields() or something similar which each of the implementing classes must implement. Then, through the magic of polymorphism, you can now treat all of your objects as DTO using typecasting and call setFields() on them without worrying what the actual object is. The setFields() method in each of the individual classes will take care of it for you.
Alternatively, you can make an enum that is essentially an ID for each of your classes and make each class have a global variable of that type (complete with getters and setters) in order to identify it. This is a somewhat "hacky" workaround but still a doable one.
How about creating a single ObjectConversionHelper class for each DTO class? Each of them could implement a common conversion interface differently, call inherited members etc. You could then make use of some object creation factory that would create relevant Helper for DTO and vice-versa (i.e. using reflection mechanizms).

Adding functions to Java class libraries

I'm using a Java class library that is in many ways incomplete: there are many classes that I feel ought to have additional member functions built in. However, I am unsure of the best practice of adding these member functions.
Lets call the insufficient base class A.
class A
{
public A(/*long arbitrary arguments*/)
{
//...
}
public A(/*long even more arbitrary arguments*/)
{
//...
}
public int func()
{
return 1;
}
}
Ideally, I would like to add a function to A. However, I can't do that. My choice is between:
class B extends A
{
//Implement ALL of A's constructors here
public int reallyUsefulFunction()
{
return func()+1;
}
}
and
class AddedFuncs
{
public static int reallyUsefulFunction(A a)
{
return a.func()+1;
}
}
The way I see it, they both have advantages and disadvantages. The first choice gives a cleaner syntax than the second, and is more logical, but has problems: Let's say I have a third class, C, within the class library.
class C
{
public A func()
{
return new A(/*...*/);
}
}
As I see it, there is no easy way of doing this:
C c;
int useful = c.func().reallyUsefulFunction();
as the type returned by C.func() is an A, not a B, and you can't down-cast.
So what is the best way of adding a member function to a read-only library class?
Natural and frequent dilemma. Read about the composition vs inheritance alternative. Your second alternative is basically a composition, if we think that the object A is passed in the constructor instead of passing it in each method - that is, we would be using composition to implement a wrapper or decorator pattern.
The issue for class C returning a new instance of class A has no trivial solution, as you guessed, as long as class C decides to take responsability of creating the new instance. This is why one should pause and think before typing a "new" statement inside a class, if there is the possibility that this class will be subclassed. In yout example, it would be nice if you could tell class C what concrete class to return ... but how would it know to create it? Well we could pass him an object who knows how to instantiate an object of class A (or a subclass)... I guess you are enough motivated to read about Factories now, and design patterns in general.
There is no unique best answer, but if want a quick one: I'd make a wrapper, B class does not extend A but has a constructor with A as parameter, it delegates its methods (except the own) to the inside object.
When you need to call the method in class C (I'm assuming you cant touch class C), you could write: B b = new B(c.func())
Why not use Composition instead of Inheritance?
class ABetterA {
private A a;
public ABetterA() {
}
// write wrapper methods calling class' A methods and maybe doing something more
}
This way, you could also mimic multiple inheritance...
You have a third option. You could use Scala (a Java compatible language) and its traits, which are mixins by another name.
Another option similar to Brian's sugestion is to use Aspect Oriented Programming (AOP) tool, such as ApectJ, which let you "inject" additional functionality into existing classes, even binary ones. You either preprocess the library jar to get a new one with enhanced classes ("static weaving") or you can do all of this at runtime when the library classes are loaded (so called "load-time weaving"). You can check this AspectJ example.
Even though AOP is normally used to modify existing methods (before, after or around "advices" = code pieces) you can also introduce new members and methods - check AspectJ's Inter-type declarations.
Of course there is the question whether AspectJ is supported at your limited platform.

Java: Is there a way to you enforce a implementation of private methods?

I have 5 or 6 classes that I want to have follow the same basic structure internally. Really most of those that the classes should follow are just for the use of the function itself, so I really want these methods to be private.
Is there any way to achieve this? I know interfaces would work great but they won't take private members and won't allow you to redefine the scope in the implemented method. Is there any workaround for this?
Thanks
I think the closest you can get is using an abstract class with abstract protected methods:
abstract class A {
protected abstract void foo();
}
class B extends A {
protected void foo() {}
}
To define common logic, you can call the protected method from a private method in the super class:
abstract class A {
private void bar() {
// do common stuff
foo();
}
protected abstract void foo();
}
This way, you can allow subclasses to fill the private common template method with specific behavior.
Create an abstract base class that outlines the structure and common flow. Specify abstract methods for the steps in the flow that must be implemented by the inheriting classes.
Hmm, private functions can't be called by any other classes, even by subclasses. So what's the point in having private functions with the same name in different classes?
There is no way to enforce it at compile time, but you can write a unit test or a simple program to test for the existence of the methods using reflection.
I assume you are doing this to make the classes consistent for aesthetics/design reasons. If you are doing it for some other reason you should really use the abstract protected way others are suggesting.
Here is some code to get you started on such a tool/unit tests (you should improve the error messages at the very least, and I would really suggest unit tests rather then what I have here):
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Main
{
public static void main(String[] args)
{
check(B.class, Modifier.PRIVATE, void.class, "doit", new Class<?>[] { int.class });
check(C.class, Modifier.PRIVATE, void.class, "doit", new Class<?>[] { int.class });
}
private static void check(final Class<?> clazz,
final int modifiers,
final Class<?> returnType,
final String name,
final Class<?>[] params)
{
try
{
final Method method;
method = clazz.getDeclaredMethod(name, params);
if(method.getModifiers() != modifiers)
{
System.out.println("modifiers do not match");
}
if(method.getReturnType() != returnType)
{
System.out.println("return type does not match");
}
}
catch(final NoSuchMethodException ex)
{
System.out.println("could not find method");
}
}
}
interface A
{
void foo();
}
class B
implements A
{
public void foo()
{
doit(0);
}
private void doit(final int x)
{
}
}
class C
implements A
{
public void foo()
{
doit(0);
}
private int doit(final int x)
{
return (5);
}
}
Create an outline 'common' class, with all your private methods on them.
Then create your 5 or 6 classes , each which have a field on there of type 'common'.
You won't be able to call the private methods of course (but you say these are really internal to the class) - you'll have to advertise some public methods to alter state as well of course.
public class common {
private method1() { ; }
private method2() { ; }
public other() { ; }
...
}
public class myclass1 {
common commonMethods;
}
public class myclass2 {
common commonMethods;
}
or even (assume 'common' is defined as above):
public class template {
common commonMethods;
}
public class myclass1 extends template {
...
}
So you get a (package-protected) 'commonMethods' field for 'free' on each of 5 or 6 subclasses.
After subsequent discussion on this thread, it appears the author doesn't actually want to share logic : just method signatures essentially , so this answer doesn't fit with that requirement.
While the interface methods themselves must always be public, you could make the interface package private and keep all of your Car (for example) implementations in the same package.
package com.some.car.pkg;
interface Car
{
public void gas();
public void brake();
}
Even though the methods are public, it doesn't matter since outside of the package com.some.car.pkg, Car is not visible. This way, all of your implementers would not be forced to extend an abstract class. The fact that you want common methods means truly private isn't the real solution, and IMHO, you want an interface, since it sounds like in your case an abstract class isn't quite right as there is no shared logic.
My 2 cents.
The "throw MethodNotImplementedException();" might be a useful construct.
If abstract protected really isn't protected enough, I wonder what the concern is. In any case, an alternative similar to monojohnny's would be to use the strategy pattern. This ensures that:
derived classes must define the behavior
derived classes can't access the behavior after defining it
instances can't access one another's behavior
E.g., with apologies for borrowing the car metaphor despite no automotive chops:
public interface GearBoxStrategy {
public void changeGear(int newGear);
}
abstract public class Car {
private GearBoxStrategy gearBox;
public Car(GearBoxStrategy g) {
this.gearBox = g;
}
public void accelerate(double targetSpeed) {
int gear = getTargetGear(targetSpeed):
gearBox.shift(gear);
}
}
public class AutomaticTransmissionCar {
public AutomaticTransmissionCar() {
super(new AutomaticTransmissionGearBoxStrategy());
}
}
public class ManualTransmissionCar {
public ManualTransmissionCar() {
super(new ManualTransmissionGearBoxStrategy());
}
}
Create an abstract base class with a method marked final that describes the common flow that includes your private methods. Marking it as final means that it can't be extended by subclasses and thus the business logic is enforced as long as your calling code utilizes it. Extension points can be created by marking methods as protected. For example say you have a class that represents a retail store.
private final void doTransaction() {
float amountDue;
// a protected or abstract method that extenders can override
Collection items = this.unloadShoppingCart();
for (Object item : items) {
// another protected or abstract method
amountDue += this.getPrice(item);
}
// your private method
amountDue += this.getSalesTax(amountDue);
}
Is it possible to make all the classes inherit from the same base class?
If so, one thing you could consider would be at runtime in the base class's constructor use reflection to validate that the subclass is following the rules you describe, and throw an exception if it fails your validation rules.
The naive implementation of this test of course would have significant performance issues, so you'd have to be pretty clever about the way you implement the test.
For a start, the test should only be run once for all instances of a particular subtype T. So, you would have to cache the validation information somewhere. One way to do this would be to use some kind of static (global) hash table in the base class keyed on the type of each subtype.
You would also have to perform some kind of thread safe synchronization around this cache. What you really need to avoid on this is a performance hit for reads. What I've done in a similar case before was use a combination of the double check locking pattern and the use of an immutable hashtable so that you only take a performance hit for locking when attempting to write to the hashtable (i.e. when you create the first instance of a particular subtype T).
I'm actually not experienced in Java, what I describe, I implemented in .NET, which is why I can't provide you with a code example, but all the concepts should be easily transferable to Java - everything I mention is (AFAIK) available on both platforms.
Take a look at XDepend, it uses reflection to create a database based on your compiled code.
http://www.xdepend.com
It's aimed at software architects who wish to be able to quickly check potentially large libraries of compiled code for potential problem areas. It has inbuilt reports and visualization for such things as relationships between classes, cyclomatic complexity, coupling etc. etc.
In addition, it includes an inbuilt sql like query language "CQL" (for "code query language"). Using CQL you can define your own reports. You probably should be able to use it to define a report for violations of the rules you describe. Also, you can embed CQL queries directly into your code using annotations.
I haven't looked into it, but have used it's .NET equivalent 'NDepend', and it's a very cool tool.
Of course, you could also write your own custom tool which uses reflection to check your specific rules. XDepend may still be worth looking at though - it should be a lot more flexible.
Here's an idea: write a simple text parser to check for the existence of the methods. Include it as a task in Ant. As long as you are insisting on some form of coding standard, some simple text-matching should do it, ie, simply look for the formatted signature in the required source files.
In a comment you wrote "Yes that is the whole point. I know they can be called different things but I don't want them to be."
Now, some people might just say "that's impossible" but like most things in programming, it's not actually impossible, it's just a lot of work.
If you really want to do this, you can create a custom Java Annotation for your class and then write an Annotation processor and call apt as part of your build process.
Like I said a lot of work, but it might be worthwhile if you want to learn how Annotations work.
Writing annotations is actually pretty simple. They work kind of like regular classes. For example, if you just want to mark a class for some reason you can create an empty or marker annotation like this
public #interface Car { }
Then in your Annotation Processor you can check to make sure Car has the right private methods.
I've written my own annotations, but I checked them at Runtime using the reflection API, rather then at build time. They are actually pretty easy.

Categories