您可以创建自己的注释:
@Retention(RetentionPolicy.RUNTIME)
public @interface Challenge {
public String key() default "";
}
那么你可以使用反思 https://github.com/ronmamo/reflections获取所有带注释的类。
Set<Class<?>> challengeClasses = reflections.getTypesAnnotatedWith(Challenge.class);
然后您可以通过以下方式提取密钥:
String key = challengeClass.getAnnotation(Challenge.class).key();
但请注意,只有在确实必要时才应谨慎使用反射。使用它你就会失去对代码正确性的控制。
Example:
com.test.webapp.Main
package com.test.testapp;
import com.test.testapp.annotations.Challenge;
import org.reflections.Reflections;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Reflections reflections = new Reflections("com.test.testapp");
Set<Class<?>> challengeClasses = reflections.getTypesAnnotatedWith(Challenge.class);
Map challengeClassesMap = challengeClasses.stream().collect(
Collectors.toMap(
challengeClass -> challengeClass.getAnnotation(Challenge.class).key(),
Main::createNewInstanceOfClass
)
);
challengeClassesMap.forEach(
(key, challengeClass) -> System.out.println(key + " = " + challengeClass.toString())
);
}
private static <T> T createNewInstanceOfClass(Class<T> someClass) {
try {
return someClass.newInstance();
} catch (Exception e) {
return null; //Bad idea but now it's waste of time
}
}
}
com.test.testapp.annotations.Challenge
package com.test.testapp.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Challenge {
public String key();
}
com.test.testapp.challenges.SomeChallenge
package com.test.testapp.challenges;
import com.test.testapp.annotations.Challenge;
@Challenge(key = "some_challenge")
public class SomeChallenge {
public String name = "Some Challenge";
@Override
public String toString() {
return "SomeChallenge{" +
"name='" + name + '\'' +
'}';
}
}
com.test.testapp.challenges.AnotherChallenge
package com.test.testapp.challenges;
import com.test.testapp.annotations.Challenge;
@Challenge(key = "another_challenge")
public class AnotherChallenge {
public String name = "Another Challenge";
@Override
public String toString() {
return "AnotherChallenge{" +
"name='" + name + '\'' +
'}';
}
}
pom.xml 依赖项(我使用的是 Maven)
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</dependency>
Output
some_challenge = SomeChallenge{name='Some Challenge'}
another_challenge = AnotherChallenge{name='Another Challenge'}
我没有更多的代码了。目录与包相同。