2

I would like to annotite java package using simple annotation:

@Target(ElementType.PACKAGE) public @interface Related { int apiVersion() default 0; } 

However when I try to add it to any package I've got compilation error

Error:(1, 14) java: cannot find symbol symbol: class Related location: package com.test.xxx 

Any help appreciated!

EDIT

After searching a bit I found also this kind of error

Error:(1, 1) java: package annotations should be in file package-info.java 
2
  • Is there only one error produced by comiler? Commented Aug 15, 2016 at 23:12
  • 1
    thank you for quick answer! no, I found another one - Error:(1, 1) java: package annotations should be in file package-info.java Commented Aug 15, 2016 at 23:13

1 Answer 1

1

To be able to place annotation on package you should create package-info.java file which should contain package definition like this:

@Related package tld.some.name; 

To be able to reflect reflect package you also need to set up RetentionPolicy.RUNTIME

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PACKAGE) public @interface Related { // stuff... } 

And then you can finally reflect package:

SomeClassInPackage.class.getPackage().getAnnotation(Related.class) 

You can also reflect package by name using java.lang.Package

Package.getPackage("tld.some.name").getAnnotation(Related.class) 
Sign up to request clarification or add additional context in comments.

1 Comment

But how can I reflect package based on string package name?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.