How should message generators identify themselves in Java?

I have a unified message object queue with multiple producers and one consumer Consumers are publishing information and need to be able to grant access according to the source of the data, so I want producers to send appropriate identifiers and messages Producers themselves cannot be held responsible for remote access restrictions

The ID should be related to the role of the generator in my application I want to force all producers to define one, and subclass generators can choose to inherit or redefine it The producer's class name is a good approximation, but the attribute I want to identify is not inherent in the class structure, but something I define

I can use reflection to find class or interface names, but it's a bit too expensive Besides, I'm not sure what the appropriate property to look for is

Since all generators are subclasses of the same abstract parent class, I think a good way is to place a constant there (or in the interface), but later I realized that in Java, "constant" is actually a "static end", which means that I can't overwrite it, so it won't work like that

How will a more experienced Java programmer do this?

Solution

If you need to identify a "type", define a mandatory class to provide you with an interface of that type, and then implement the interface anywhere

Example:

public interface IHasType {
   public String getTypeId();
}

However, if the type list is fixed, I will go further and make the type enumeration:

public enum MyType {
   TYPE_A,TYPE_B;
}

Then return this enumeration instead of string

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>