Search code examples
c#javaattributesequivalent

Java equivalent for AttributeUsage C#


I have to translate some code from C# to Java and I have the following piece of code :

 [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class PVAResponseAttribute : XmlRootAttribute
    {
        private const string ROOT_ELEMENT_NAME = "data";

        public PVAResponseAttribute()
            : base(ROOT_ELEMENT_NAME)
        {

        }

What's the equivalent in Java for this ? Thank you


Solution

  • Whilst it is true that Java's annotations share a lot in common with C# attributes, the OP is asking a specific question.

    There's no direct equivalent in Java of the C# AttributesUsage attribute. This is a C# core attribute that you apply when creating your own custom attributes. It is used to control the behaviour of your attribute.

    You use it to:

    • Limit the possible targets of your attribute. See the AttributeTargets enumeration for the various options.
    • Decide if the attribute will apply to inherited members
    • Decide if you are allowed to this attribute multiple times on the same member

    In this case, the author of the C# code has stuck with the defaults. The custom attribute they have written can be applied to any class and does not have interesting behaviour with respect to inheritance members (it applies to inherited members) and if it can be used multiple times on a member (it can't).

    To port this code to Java you need to create a Java annotation that does the same as the author's C# PVAResponseAttribute attribute.

    However, in this case you don't need to worry that there isn't a Java annotation that is a direct equivalent of C# AttributesUsage attribute.