下面列出了org.junit.jupiter.params.provider.EnumSource#java.lang.annotation.ElementType 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Inspects a class annotation.
*
* @param cf {@code non-null;} class file
* @param ann {@code non-null;} annotation
*/
private void visitClassAnnotation(DirectClassFile cf,
BaseAnnotations ann) {
if (!args.eTypes.contains(ElementType.TYPE)) {
return;
}
for (Annotation anAnn : ann.getAnnotations().getAnnotations()) {
String annClassName
= anAnn.getType().getClassType().getClassName();
if (args.aclass.equals(annClassName)) {
printMatch(cf);
}
}
}
@Check
public void checkAnnotationTarget(XAnnotation annotation) {
JvmType annotationType = annotation.getAnnotationType();
if (annotationType == null || annotationType.eIsProxy() || !(annotationType instanceof JvmAnnotationType)) {
return;
}
Set<ElementType> targets = annotationUtil.getAnnotationTargets((JvmAnnotationType) annotationType);
if (targets.isEmpty())
return;
final EObject eContainer = getContainingAnnotationTarget(annotation);
Class<? extends EObject> clazz = eContainer.getClass();
if (eContainer instanceof XtendField && eContainer.eContainer() instanceof XtendAnnotationType) {
clazz = XtendFunction.class;
}
for (Entry<Class<?>, Collection<ElementType>> mapping : targetInfos.asMap().entrySet()) {
if (mapping.getKey().isAssignableFrom(clazz)) {
targets.retainAll(mapping.getValue());
if (targets.isEmpty()) {
error("The annotation @" + annotation.getAnnotationType().getSimpleName()
+ " is disallowed for this location.", annotation, null, INSIGNIFICANT_INDEX,
ANNOTATION_WRONG_TARGET);
}
}
}
}
/**
* 从本地的Json文件加载
*/
public static ExtensionImpl newExtension(ExtensionPointImpl point,
Class<?> clazz, Member member, JSONObject json)
throws ReflectiveOperationException {
ExtensionImpl extension = new ExtensionImpl();
if (json != null) {
extension.setConfig(json);
}
extension.setPoint(point);
extension.setRefClass(clazz);
extension.setElementName(member.getName());
extension.setElementType(member instanceof Method ? ElementType.METHOD
: ElementType.FIELD);
// 校验、补全
validate(extension);
format(extension);
return extension;
}
/**
* 从注解加载
*/
public static ExtensionImpl newExtension(ExtensionPointImpl point,
Class<?> clazz, Member member, Annotation annotation)
throws ReflectiveOperationException {
ExtensionImpl extension = new ExtensionImpl();
JSONObject json = PluginReflectUtil.annotationToJson(annotation);
if (point.getConfig() != null) {
extension.setConfig(json);
}
extension.setPoint(point);
extension.setRefClass(clazz);
extension.setElementName(member.getName());
extension.setElementType(member instanceof Method ? ElementType.METHOD
: ElementType.FIELD);
// 校验、补全
validate(extension);
format(extension);
return extension;
}
/**
* 从本地的Json文件加载
*/
public static ExtensionImpl newExtension(ExtensionPointImpl point,
Class<?> clazz, JSONObject json)
throws ReflectiveOperationException {
ExtensionImpl extension = new ExtensionImpl();
if (json != null) {
extension.setConfig(json);
}
extension.setPoint(point);
extension.setRefClass(clazz);
extension.setElementType(ElementType.TYPE);
// 校验、补全
validate(extension);
format(extension);
return extension;
}
/**
* 从注解加载
*/
public static ExtensionImpl newExtension(ExtensionPointImpl point,
Class<?> clazz, Annotation annotation)
throws ReflectiveOperationException {
ExtensionImpl extension = new ExtensionImpl();
JSONObject json = PluginReflectUtil.annotationToJson(annotation);
if (point.getConfig() != null) {
extension.setConfig(json);
}
extension.setPoint(point);
extension.setRefClass(clazz);
extension.setElementType(ElementType.TYPE);
// 校验、补全
validate(extension);
format(extension);
return extension;
}
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
when(otherLegal.accept(any(TypeDescription.Generic.Visitor.class))).thenReturn(true);
when(otherIllegal.accept(any(TypeDescription.Generic.Visitor.class))).thenReturn(false);
when(illegal.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(illegalAnnotation));
when(illegalAnnotation.getElementTypes()).thenReturn(new HashSet<ElementType>());
when(illegalAnnotation.getAnnotationType()).thenReturn(illegalType);
when(otherLegal.asGenericType()).thenReturn(otherLegal);
when(otherIllegal.asGenericType()).thenReturn(otherIllegal);
try {
Enum<?> typeUse = Enum.valueOf(ElementType.class, "TYPE_USE");
Enum<?> typeParameter = Enum.valueOf(ElementType.class, "TYPE_PARAMETER");
when(legalAnnotation.getElementTypes()).thenReturn(new HashSet(Arrays.asList(typeUse, typeParameter)));
when(duplicateAnnotation.getElementTypes()).thenReturn(new HashSet(Arrays.asList(typeUse, typeParameter)));
} catch (IllegalArgumentException ignored) {
when(legalAnnotation.getElementTypes()).thenReturn(Collections.<ElementType>emptySet());
when(duplicateAnnotation.getElementTypes()).thenReturn(Collections.<ElementType>emptySet());
}
when(legal.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(legalAnnotation));
when(duplicate.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(legalAnnotation, duplicateAnnotation));
when(legalAnnotation.getAnnotationType()).thenReturn(legalType);
when(duplicateAnnotation.getAnnotationType()).thenReturn(legalType);
}
/**
* Simple helper method to essentially clone the annotations from one class onto another.
*/
public static void copyClassAnnotations(final CtClass oldClass, final CtClass newClass) {
// Load the existing annotations attributes
final AnnotationsAttribute classAnnotations =
(AnnotationsAttribute) oldClass.getClassFile().getAttribute(
AnnotationsAttribute.visibleTag);
// Clone them
final AnnotationsAttribute copyClassAttribute =
JavassistUtils.cloneAnnotationsAttribute(
newClass.getClassFile2().getConstPool(),
classAnnotations,
ElementType.TYPE);
// Set the annotations on the new class
newClass.getClassFile().addAttribute(copyClassAttribute);
}
@Test
public void testGetEnumInvalid() {
args.put("key", "CONSTRUCTOR");
Set<ElementType> all = EnumSet.noneOf(ElementType.class);
all.add(ElementType.FIELD);
all.add(ElementType.METHOD);
System.out.print(all);
try {
ctx.getEnum("key", all);
fail("IllegalArgumentException expected.");
} catch (IllegalArgumentException e) {
assertEquals(
"Invalid parameter value 'CONSTRUCTOR' for key. Valid values are [FIELD, METHOD].",
e.getMessage());
}
}
private boolean readAttributes(DataInput di, ElementType type) throws IOException {
final int count = di.readUnsignedShort();
for (int i = 0; i < count; ++i) {
final String name = resolveUtf8(di);
// in bytes, use this to skip the attribute info block
final int length = di.readInt();
if (type == ElementType.TYPE && ("RuntimeVisibleAnnotations".equals(name) || "RuntimeInvisibleAnnotations".equals(name))) {
if (readAnnotations(di)) {
return true;
}
} else {
di.skipBytes(length);
}
}
return false;
}
/**
* Note that:
*
* <pre>
* If no annotation matches the specified parameter, the property will be ignored.
* </pre>
*
* @param key
* @param expectedType
* @return the configured value
*/
private <U> U lookup(String key, Class<U> expectedType) {
Config config = getConfig();
Optional<U> value;
if (ElementType.METHOD.equals(annotationSource)) {
// <classname>/<methodname>/<annotation>/<parameter>
value = config.getOptionalValue(getConfigKeyForMethod() + key, expectedType);
} else {
// <classname>/<annotation>/<parameter>
value = config.getOptionalValue(getConfigKeyForClass() + key, expectedType);
}
if (!value.isPresent()) {
// <annotation>/<parameter>
value = config.getOptionalValue(annotationType.getSimpleName() + "/" + key, expectedType);
}
// annotation values
return value.orElseGet(() -> getConfigFromAnnotation(key));
}
/**
* Inspects a class annotation.
*
* @param cf {@code non-null;} class file
* @param ann {@code non-null;} annotation
*/
private void visitClassAnnotation(DirectClassFile cf,
BaseAnnotations ann) {
if (!args.eTypes.contains(ElementType.TYPE)) {
return;
}
for (Annotation anAnn : ann.getAnnotations().getAnnotations()) {
String annClassName
= anAnn.getType().getClassType().getClassName();
if (args.aclass.equals(annClassName)) {
printMatch(cf);
}
}
}
/**
* Inspects a class annotation.
*
* @param cf {@code non-null;} class file
* @param ann {@code non-null;} annotation
*/
private void visitClassAnnotation(DirectClassFile cf,
BaseAnnotations ann) {
if (!args.eTypes.contains(ElementType.TYPE)) {
return;
}
for (Annotation anAnn : ann.getAnnotations().getAnnotations()) {
String annClassName
= anAnn.getType().getClassType().getClassName();
if (args.aclass.equals(annClassName)) {
printMatch(cf);
}
}
}
/**
* @throws Exception
* @tests java.lang.annotation.ElementType#valueOf(String)
*/
@SuppressWarnings("nls")
public void test_valueOfLjava_lang_String() throws Exception {
assertSame(ElementType.ANNOTATION_TYPE, ElementType
.valueOf("ANNOTATION_TYPE"));
assertSame(ElementType.CONSTRUCTOR, ElementType.valueOf("CONSTRUCTOR"));
assertSame(ElementType.FIELD, ElementType.valueOf("FIELD"));
assertSame(ElementType.LOCAL_VARIABLE, ElementType
.valueOf("LOCAL_VARIABLE"));
assertSame(ElementType.METHOD, ElementType.valueOf("METHOD"));
assertSame(ElementType.PACKAGE, ElementType.valueOf("PACKAGE"));
assertSame(ElementType.PARAMETER, ElementType.valueOf("PARAMETER"));
assertSame(ElementType.TYPE, ElementType.valueOf("TYPE"));
try {
ElementType.valueOf("OTHER");
fail("Should throw an IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
@Override
public boolean hasReqiredTarget( AnnotationMirror target , Set<ElementType>
targetTypes )
{
int sz = 1;
if(targetTypes.size()>0){
sz = targetTypes.size();
if(targetTypes.contains( ElementType.TYPE)){
sz--;
}
if ( targetTypes.contains( ElementType.METHOD)) {
sz--;
}
if (targetTypes.contains( ElementType.CONSTRUCTOR) )
{
sz--;
}
}
return sz==0;
}
@Test
public void testGetEnumOptionalInvalid() {
args.put("key", "CONSTRUCTOR");
Set<ElementType> all = EnumSet.noneOf(ElementType.class);
all.add(ElementType.FIELD);
all.add(ElementType.METHOD);
assertEquals(null, ctx.getEnumOptional("key", all));
}
private List<String> convertToString(Set<ElementType> annoTarget) {
if (annoTarget == null) {
return null;
}
List<String> annoTargets = new ArrayList<String>();
for (ElementType e : annoTarget) {
annoTargets.add("ElementType." + e.name());
}
return annoTargets;
}
public static boolean isJAXB22() {
Target t = XmlElement.class.getAnnotation(Target.class);
//JAXB 2.2 allows XmlElement on params.
for (ElementType et : t.value()) {
if (et == ElementType.PARAMETER) {
return true;
}
}
return false;
}
@Override
public ElementType getElementType() {
if (Const.CONSTRUCTOR_NAME.equals(getName())) {
return ElementType.CONSTRUCTOR;
}
return ElementType.METHOD;
}
private List<String> convertToString(Set<ElementType> annoTarget) {
if (annoTarget == null) {
return null;
}
List<String> annoTargets = new ArrayList<String>();
for (ElementType e : annoTarget) {
annoTargets.add("ElementType." + e.name());
}
return annoTargets;
}
/**
* 从指定集合i_Classes中,挑出有注解的Class。并分类存储。
*
* @param i_Classes Java元类型的集合
* @param i_AnnotationClass 注解类型的元类型
* @return
*/
public static PartitionMap<ElementType ,ClassInfo> getAnnotations(List<Class<?>> i_Classes ,Class<? extends Annotation> i_AnnotationClass)
{
PartitionMap<ElementType ,ClassInfo> v_Ret = new TablePartition<ElementType ,ClassInfo>();
for (int i=0; i<i_Classes.size(); i++)
{
Class<?> v_Class = i_Classes.get(i);
ClassInfo v_ClassInfo = new ClassInfo(v_Class); // 为了在多个分区引用同一对象,所以在此无论是否被注解都new
// 判断类是否注解
if ( v_Class.isAnnotationPresent(i_AnnotationClass) )
{
v_Ret.putRow(ElementType.TYPE ,v_ClassInfo);
}
// 判断类中的自有方法是否注解
List<Method> v_Methods = MethodReflect.getAnnotationMethods(v_Class ,i_AnnotationClass);
if ( !Help.isNull(v_Methods) )
{
v_ClassInfo.setMethods(v_Methods);
v_Ret.putRow(ElementType.METHOD ,v_ClassInfo);
}
// 判断类中的自有属性是否注解
List<Field> v_Fields = getAnnotationFields(v_Class ,i_AnnotationClass);
if ( !Help.isNull(v_Fields) )
{
v_ClassInfo.setFields(v_Fields);
v_Ret.putRow(ElementType.FIELD ,v_ClassInfo);
}
}
return v_Ret;
}
@Test
public void Annotation_can_only_be_applied_to_fields() {
Target target = Fixture.class.getAnnotation(Target.class);
assertEquals(1, target.value().length);
ElementType type = target.value()[0];
assertEquals(ElementType.FIELD, type);
}
/**
* Tests that when CopyAnnotationsToGeneratedField is present on a method, all non-inherited
* annotations (except those appearing in CopyAnnotationsToGeneratedField.exclude) are copied to
* the method implementation in the generated class.
*/
@Test
public void testCopyingMethodAnnotationsToGeneratedFields() {
JavaFileObject inputFile =
new InputFileBuilder()
.setImports(getImports(PropertyAnnotationsTest.class, Target.class, ElementType.class))
.addAnnotations(
"@AutoValue.CopyAnnotations(exclude={PropertyAnnotationsTest."
+ "TestAnnotation.class})",
"@Deprecated",
"@PropertyAnnotationsTest.TestAnnotation",
"@PropertyAnnotationsTest.InheritedAnnotation",
"@MethodsOnly")
.addInnerTypes("@Target(ElementType.METHOD) @interface MethodsOnly {}")
.build();
JavaFileObject outputFile =
new OutputFileBuilder()
.setImports(getImports(PropertyAnnotationsTest.class))
.addFieldAnnotations("@Deprecated", "@PropertyAnnotationsTest.InheritedAnnotation")
.addMethodAnnotations(
"@Deprecated",
"@PropertyAnnotationsTest.InheritedAnnotation",
"@Baz.MethodsOnly")
.build();
assertAbout(javaSource())
.that(inputFile)
.processedWith(new AutoValueProcessor())
.compilesWithoutError()
.and()
.generatesSources(outputFile);
}
public Entry(
String annotationType,
ElementType targetType,
String targetInClass,
String target
) {
this.annotationType = annotationType;
this.targetType = targetType;
this.targetInClass = targetInClass;
this.target = target;
}
/** Start ElementType Type Related Integration Test */
@Test(dataProvider = ENDPOINTS_DATAPROVIDER, description = "Tests if an public action method with ElementType param can be called")
public void testCallPublicMethodWithElementTypeParams(String containerType, String endpoint) {
final ElementType value = ElementType.PARAMETER;
performActionForElementType(containerType, endpoint, PUBLIC_WITH_ELEMENT_TYPE_PARAM_ACTION, value, new Param(PARAM_NAME, value));
}
/**
* Inspects a package annotation
*
* @param cf {@code non-null;} class file of "package-info" pseudo-class
* @param ann {@code non-null;} annotation
*/
private void visitPackageAnnotation(
DirectClassFile cf, BaseAnnotations ann) {
if (!args.eTypes.contains(ElementType.PACKAGE)) {
return;
}
String packageName = cf.getThisClass().getClassType().getClassName();
int slashIndex = packageName.lastIndexOf('/');
if (slashIndex == -1) {
packageName = "";
} else {
packageName
= packageName.substring(0, slashIndex);
}
for (Annotation anAnn : ann.getAnnotations().getAnnotations()) {
String annClassName
= anAnn.getType().getClassType().getClassName();
if (args.aclass.equals(annClassName)) {
printMatchPackage(packageName);
}
}
}
private Set<ElementType> less(Set<ElementType> base, ElementType... sub) {
Set<ElementType> res = EnumSet.noneOf(ElementType.class);
res.addAll(base);
for (ElementType t : sub) {
res.remove(t);
}
return res;
}
private List<String> convertToString(Set<ElementType> annoTarget) {
if (annoTarget == null) {
return null;
}
List<String> annoTargets = new ArrayList<String>();
for (ElementType e : annoTarget) {
annoTargets.add("ElementType." + e.name());
}
return annoTargets;
}
public static Set<ElementType> getDeclaredTargetTypes(
AnnotationHelper helper, TypeElement element )
{
Map<String, ? extends AnnotationMirror> types = helper
.getAnnotationsByType(element.getAnnotationMirrors());
AnnotationMirror target = types.get(Target.class.getCanonicalName());
if (target == null) {
return Collections.emptySet();
}
return getDeclaredTargetTypes( helper, target );
}
private Set<ElementType> plus(Set<ElementType> base, ElementType... add) {
Set<ElementType> res = EnumSet.noneOf(ElementType.class);
res.addAll(base);
for (ElementType t : add) {
res.add(t);
}
return res;
}