Andrew Cheong
Andrew Cheong

Reputation: 30273

Proper use of Java annotations to generate classes based on imported, external library classes

Given some imported classes that I cannot affect,

import com.foo.A;
import com.foo.B;
import com.foo.C;

I want to generate an interface of methods shared by A, B, and C, e.g.

public interface Common {
    Uuid getId();
    Long getVersion();
    DateTime getCreated();
    DateTime getModified();
}

and also generate proxy classes implementing this interface;

public class A extends com.foo.A implements Common {}
public class B extends com.foo.B implements Common {}
public class C extends com.foo.C implements Common {}

It seems like I should use Java annotations and JavaPoet to achieve this, but I don't know what the annotated target should be. That is, I want to write something like

@GenerateRelatedProxies("Common", com.foo.A, com.foo.B, com.foo.C)

but, what element should this annotation be annotating? Should I be using annotations at all, or how would you approach this kind of code generation?


If the classes are related, then why doesn't the library provide an interface to begin with?

The reason is that the library is generated from proto3. My understanding is that protobuf doesn't support inheritance because it desires to be language agnostic, and some languages don't support inheritance (e.g. Rust). However, conceptually, the classes I'm working with are practically as related as Cat, Dog, and Bird, and it's getting seriously annoying to copy-paste identical logic everywhere in Java because of a reliance on protobuf-generated classes. I think it's valid for me to organize implementation code as I wish, granted I am asserting that Cat, Dog, and Bird are in fact related.

Upvotes: 1

Views: 7159

Answers (0)

Related Questions