javassist.bytecode.AnnotationsAttribute Java Examples

The following examples show how to use javassist.bytecode.AnnotationsAttribute. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CtMethodBuilder.java    From japicmp with Apache License 2.0 6 votes vote down vote up
public CtMethod addToClass(CtClass declaringClass) throws CannotCompileException {
	if (this.returnType == null) {
		this.returnType = declaringClass;
	}
	CtMethod ctMethod = CtNewMethod.make(this.modifier, this.returnType, this.name, this.parameters, this.exceptions, this.body, declaringClass);
	ctMethod.setModifiers(this.modifier);
	declaringClass.addMethod(ctMethod);
	for (String annotation : annotations) {
		ClassFile classFile = declaringClass.getClassFile();
		ConstPool constPool = classFile.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		Annotation annot = new Annotation(annotation, constPool);
		attr.setAnnotation(annot);
		ctMethod.getMethodInfo().addAttribute(attr);
	}
	return ctMethod;
}
 
Example #2
Source File: ClassPathScanner.java    From Bats with Apache License 2.0 6 votes vote down vote up
private List<AnnotationDescriptor> getAnnotationDescriptors(AnnotationsAttribute annotationsAttr) {
  if (annotationsAttr == null) {
    return Collections.emptyList();
  }
  List<AnnotationDescriptor> annotationDescriptors = new ArrayList<>(annotationsAttr.numAnnotations());
  for (javassist.bytecode.annotation.Annotation annotation : annotationsAttr.getAnnotations()) {
    // Sigh: javassist uses raw collections (is this 2002?)
    Set<String> memberNames = annotation.getMemberNames();
    List<AttributeDescriptor> attributes = new ArrayList<>();
    if (memberNames != null) {
      for (String name : memberNames) {
        MemberValue memberValue = annotation.getMemberValue(name);
        final List<String> values = new ArrayList<>();
        memberValue.accept(new ListingMemberValueVisitor(values));
        attributes.add(new AttributeDescriptor(name, values));
      }
    }
    annotationDescriptors.add(new AnnotationDescriptor(annotation.getTypeName(), attributes));
  }
  return annotationDescriptors;
}
 
Example #3
Source File: ProviderSupplierBrideBuilder.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Class<? extends Supplier<T>> build() {
    ClassPool classPool = ClassPool.getDefault();
    CtClass classBuilder = classPool.makeClass(providerClass.getCanonicalName() + "$Bride" + INDEX.incrementAndGet());
    try {
        classBuilder.addInterface(classPool.get(Supplier.class.getName()));
        ConstPool constPool = classBuilder.getClassFile().getConstPool();
        CtField field = CtField.make(String.format("%s provider;", Types.className(providerClass)), classBuilder);
        Annotation ctAnnotation = new Annotation(Inject.class.getCanonicalName(), constPool);
        AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
        attr.addAnnotation(ctAnnotation);
        field.getFieldInfo().addAttribute(attr);
        classBuilder.addField(field);

        CtMethod ctMethod = CtMethod.make("public Object get() {return provider.get();}", classBuilder);
        classBuilder.addMethod(ctMethod);

        return classBuilder.toClass();
    } catch (CannotCompileException | NotFoundException e) {
        throw new ApplicationException("failed to create provider bride, providerType={}", providerClass, e);
    }
}
 
Example #4
Source File: SwaggerMoreDoclet.java    From swagger-more with Apache License 2.0 6 votes vote down vote up
private static void annotateApiAnn(ApiInfo info, AnnotationsAttribute attr, ConstPool constPool) {
    Annotation apiAnn = attr.getAnnotation(Api.class.getTypeName());
    MemberValue value;
    if (isNull(apiAnn)) {
        apiAnn = new Annotation(Api.class.getName(), constPool);
    }
    if (isNull(value = apiAnn.getMemberValue(ApiInfo.HIDDEN)) || !((BooleanMemberValue) value).getValue()) {
        apiAnn.addMemberValue(ApiInfo.HIDDEN, new BooleanMemberValue(info.hidden(), constPool));
    }
    ArrayMemberValue arrayMemberValue = (ArrayMemberValue) apiAnn.getMemberValue(TAGS);
    if (isNull(arrayMemberValue)) {
        arrayMemberValue = new ArrayMemberValue(constPool);
        arrayMemberValue.setValue(new MemberValue[1]);
    }
    StringMemberValue tagMemberValue = (StringMemberValue) arrayMemberValue.getValue()[0];
    if (isNull(tagMemberValue) || StringUtils.isEmpty(tagMemberValue.getValue())) {
        tagMemberValue = new StringMemberValue(info.tag(), constPool);
    }
    tagMemberValue.setValue(info.tag());
    arrayMemberValue.getValue()[0] = tagMemberValue;
    apiAnn.addMemberValue(TAGS, arrayMemberValue);
    attr.addAnnotation(apiAnn);
}
 
Example #5
Source File: JavassistProxy.java    From gadtry with Apache License 2.0 6 votes vote down vote up
/**
 * 添加方法
 */
private static void addProxyMethod(CtClass proxy, CtMethod parentMethod, String methodBody)
        throws NotFoundException, CannotCompileException
{
    int mod = Modifier.FINAL | parentMethod.getModifiers();
    if (Modifier.isNative(mod)) {
        mod = mod & ~Modifier.NATIVE;
    }

    CtMethod proxyMethod = new CtMethod(parentMethod.getReturnType(), parentMethod.getName(), parentMethod.getParameterTypes(), proxy);
    proxyMethod.setModifiers(mod);
    proxyMethod.setBody(methodBody);

    //add Override
    Annotation annotation = new Annotation(Override.class.getName(), proxyMethod.getMethodInfo().getConstPool());
    AnnotationsAttribute attribute = new AnnotationsAttribute(proxyMethod.getMethodInfo().getConstPool(), AnnotationsAttribute.visibleTag);
    attribute.addAnnotation(annotation);
    proxyMethod.getMethodInfo().addAttribute(attribute);

    try {
        proxy.addMethod(proxyMethod);
    }
    catch (DuplicateMemberException e) {
        //todo: Use a more elegant way
    }
}
 
Example #6
Source File: JavassistProxy.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
/**
 * 代理缓存字段
 * 
 * <pre>
 * private final [clazz.name] _object;
 * private final CacheManager _manager;
 * </pre>
 * 
 * @param clazz
 * @param proxyClass
 * @throws Exception
 */
private void proxyCacheFields(Class<?> clazz, CtClass proxyClass) throws Exception {
    ConstPool constPool = proxyClass.getClassFile2().getConstPool();
    CtField managerField = new CtField(classPool.get(ProxyManager.class.getName()), FIELD_MANAGER, proxyClass);
    CtField informationField = new CtField(classPool.get(CacheInformation.class.getName()), FIELD_INFORMATION, proxyClass);

    List<CtField> fields = Arrays.asList(managerField, informationField);
    List<String> types = Arrays.asList("javax.persistence.Transient", "org.springframework.data.annotation.Transient");
    for (CtField field : fields) {
        field.setModifiers(Modifier.PRIVATE + Modifier.FINAL + Modifier.TRANSIENT);
        FieldInfo fieldInfo = field.getFieldInfo();
        for (String type : types) {
            AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
            Annotation annotation = new Annotation(type, constPool);
            annotationsAttribute.addAnnotation(annotation);
            fieldInfo.addAttribute(annotationsAttribute);
        }
        proxyClass.addField(field);
    }
}
 
Example #7
Source File: ClassPathScanner.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void scan(final Object cls) {
  final ClassFile classFile = (ClassFile)cls;
  AnnotationsAttribute annotations = ((AnnotationsAttribute)classFile.getAttribute(AnnotationsAttribute.visibleTag));
  if (annotations != null) {
    boolean isAnnotated = false;
    for (javassist.bytecode.annotation.Annotation a : annotations.getAnnotations()) {
      if (annotationsToScan.contains(a.getTypeName())) {
        isAnnotated = true;
      }
    }
    if (isAnnotated) {
      List<AnnotationDescriptor> classAnnotations = getAnnotationDescriptors(annotations);
      List<FieldInfo> classFields = classFile.getFields();
      List<FieldDescriptor> fieldDescriptors = new ArrayList<>(classFields.size());
      for (FieldInfo field : classFields) {
        String fieldName = field.getName();
        AnnotationsAttribute fieldAnnotations = ((AnnotationsAttribute) field.getAttribute(AnnotationsAttribute.visibleTag));
        fieldDescriptors.add(new FieldDescriptor(fieldName, field.getDescriptor(), getAnnotationDescriptors(fieldAnnotations)));
      }
      functions.add(new AnnotatedClassDescriptor(classFile.getName(), classAnnotations, fieldDescriptors));
    }
  }
}
 
Example #8
Source File: ClassFileArchiveEntryHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private ClassDescriptor toClassDescriptor(ClassFile classFile, ArchiveEntry entry) {
	ClassDescriptor.Categorization categorization = ClassDescriptor.Categorization.OTHER;;

	final AnnotationsAttribute visibleAnnotations = (AnnotationsAttribute) classFile.getAttribute( AnnotationsAttribute.visibleTag );
	if ( visibleAnnotations != null ) {
		if ( visibleAnnotations.getAnnotation( Entity.class.getName() ) != null
				|| visibleAnnotations.getAnnotation( MappedSuperclass.class.getName() ) != null
				|| visibleAnnotations.getAnnotation( Embeddable.class.getName() ) != null ) {
			categorization = ClassDescriptor.Categorization.MODEL;
		}
		else if ( visibleAnnotations.getAnnotation( Converter.class.getName() ) != null ) {
			categorization = ClassDescriptor.Categorization.CONVERTER;
		}
	}

	return new ClassDescriptorImpl( classFile.getName(), categorization, entry.getStreamAccess() );
}
 
Example #9
Source File: Proxy.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
@SneakyThrows
public Proxy<I> addField(String code, Class<? extends java.lang.annotation.Annotation> annotation, Map<String, Object> annotationProperties) {
    return handleException(() -> {
        CtField ctField = CtField.make(code, ctClass);
        if (null != annotation) {
            ConstPool constPool = ctClass.getClassFile().getConstPool();
            AnnotationsAttribute attributeInfo = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
            Annotation ann = new javassist.bytecode.annotation.Annotation(annotation.getName(), constPool);
            if (null != annotationProperties) {
                annotationProperties.forEach((key, value) -> {
                    MemberValue memberValue = createMemberValue(value, constPool);
                    if (memberValue != null) {
                        ann.addMemberValue(key, memberValue);
                    }
                });
            }
            attributeInfo.addAnnotation(ann);
            ctField.getFieldInfo().addAttribute(attributeInfo);
        }
        ctClass.addField(ctField);
    });
}
 
Example #10
Source File: JavassistAdapter.java    From panda with Apache License 2.0 6 votes vote down vote up
private List<String> getAnnotationNames(AnnotationsAttribute... annotationsAttributes) {
    List<String> result = new ArrayList<>();

    if (annotationsAttributes == null) {
        return result;
    }

    for (AnnotationsAttribute annotationsAttribute : annotationsAttributes) {
        if (annotationsAttribute == null) {
            continue;
        }

        for (Annotation annotation : annotationsAttribute.getAnnotations()) {
            result.add(annotation.getTypeName());
        }
    }

    return result;
}
 
Example #11
Source File: CtMethodBuilder.java    From japicmp with Apache License 2.0 6 votes vote down vote up
public CtMethod addToClass(CtClass declaringClass) throws CannotCompileException {
	if (this.returnType == null) {
		this.returnType = declaringClass;
	}
	CtMethod ctMethod = CtNewMethod.make(this.modifier, this.returnType, this.name, this.parameters, this.exceptions, this.body, declaringClass);
	ctMethod.setModifiers(this.modifier);
	declaringClass.addMethod(ctMethod);
	for (String annotation : annotations) {
		ClassFile classFile = declaringClass.getClassFile();
		ConstPool constPool = classFile.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		Annotation annot = new Annotation(annotation, constPool);
		attr.setAnnotation(annot);
		ctMethod.getMethodInfo().addAttribute(attr);
	}
	return ctMethod;
}
 
Example #12
Source File: ClasspathScanner.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private static boolean isAnnotated(ClassFile cfile, Class<? extends Annotation>[] annotated) {
	List attributes = U.safe(cfile.getAttributes());

	for (Object attribute : attributes) {
		if (attribute instanceof AnnotationsAttribute) {
			AnnotationsAttribute annotations = (AnnotationsAttribute) attribute;

			for (Class<? extends Annotation> ann : annotated) {
				if (annotations.getAnnotation(ann.getName()) != null) {
					return true;
				}
			}
		}
	}

	return false;
}
 
Example #13
Source File: SpringMVCBinder.java    From statefulj with Apache License 2.0 6 votes vote down vote up
@Override
protected void addEndpointMapping(CtMethod ctMethod, String method, String request) {
	MethodInfo methodInfo = ctMethod.getMethodInfo();
	ConstPool constPool = methodInfo.getConstPool();

	AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
	Annotation requestMapping = new Annotation(RequestMapping.class.getName(), constPool);

	ArrayMemberValue valueVals = new ArrayMemberValue(constPool);
	StringMemberValue valueVal = new StringMemberValue(constPool);
	valueVal.setValue(request);
	valueVals.setValue(new MemberValue[]{valueVal});

	requestMapping.addMemberValue("value", valueVals);

	ArrayMemberValue methodVals = new ArrayMemberValue(constPool);
	EnumMemberValue methodVal = new EnumMemberValue(constPool);
	methodVal.setType(RequestMethod.class.getName());
	methodVal.setValue(method);
	methodVals.setValue(new MemberValue[]{methodVal});

	requestMapping.addMemberValue("method", methodVals);
	attr.addAnnotation(requestMapping);
	methodInfo.addAttribute(attr);
}
 
Example #14
Source File: JavassistUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #15
Source File: CtClassBuilder.java    From japicmp with Apache License 2.0 6 votes vote down vote up
public CtClass addToClassPool(ClassPool classPool) {
	CtClass ctClass;
	if (this.superclass.isPresent()) {
		ctClass = classPool.makeClass(this.name, this.superclass.get());
	} else {
		ctClass = classPool.makeClass(this.name);
	}
	ctClass.setModifiers(this.modifier);
	for (String annotation : annotations) {
		ClassFile classFile = ctClass.getClassFile();
		ConstPool constPool = classFile.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		Annotation annot = new Annotation(annotation, constPool);
		attr.setAnnotation(annot);
		ctClass.getClassFile2().addAttribute(attr);
	}
	for (CtClass interfaceCtClass : interfaces) {
		ctClass.addInterface(interfaceCtClass);
	}
	return ctClass;
}
 
Example #16
Source File: JInterface.java    From jadira with Apache License 2.0 6 votes vote down vote up
@Override
public Set<JAnnotation<?>> getAnnotations() throws ClasspathAccessException {

    AnnotationsAttribute visible = (AnnotationsAttribute) getClassFile().getAttribute(AnnotationsAttribute.visibleTag);
    AnnotationsAttribute invisible = (AnnotationsAttribute) getClassFile().getAttribute(AnnotationsAttribute.invisibleTag);

    Set<JAnnotation<?>> annotations = new HashSet<JAnnotation<?>>();

    List<Annotation> annotationsList = new ArrayList<Annotation>();
    if (visible != null) {
        annotationsList.addAll(Arrays.asList(visible.getAnnotations()));
    }
    if (invisible != null) {
        annotationsList.addAll(Arrays.asList(invisible.getAnnotations()));
    }

    for (Annotation nextAnnotation : annotationsList) {
        annotations.add(JAnnotation.getJAnnotation(nextAnnotation, this, getResolver()));
    }

    return annotations;
}
 
Example #17
Source File: JClass.java    From jadira with Apache License 2.0 6 votes vote down vote up
@Override
public Set<JAnnotation<?>> getAnnotations() {

    AnnotationsAttribute visible = (AnnotationsAttribute) getClassFile().getAttribute(AnnotationsAttribute.visibleTag);
    AnnotationsAttribute invisible = (AnnotationsAttribute) getClassFile().getAttribute(AnnotationsAttribute.invisibleTag);

    Set<JAnnotation<?>> annotations = new HashSet<JAnnotation<?>>();

    List<Annotation> annotationsList = new ArrayList<Annotation>();
    if (visible != null) {
        annotationsList.addAll(Arrays.asList(visible.getAnnotations()));
    }
    if (invisible != null) {
        annotationsList.addAll(Arrays.asList(invisible.getAnnotations()));
    }

    for (Annotation nextAnnotation : annotationsList) {
        annotations.add(JAnnotation.getJAnnotation(nextAnnotation, this, getResolver()));
    }

    return annotations;
}
 
Example #18
Source File: JField.java    From jadira with Apache License 2.0 6 votes vote down vote up
@Override
public Set<JAnnotation<?>> getAnnotations() {

    AnnotationsAttribute visible = (AnnotationsAttribute) fieldInfo.getAttribute(AnnotationsAttribute.visibleTag);
    AnnotationsAttribute invisible = (AnnotationsAttribute) fieldInfo.getAttribute(AnnotationsAttribute.invisibleTag);

    Set<JAnnotation<?>> annotations = new HashSet<JAnnotation<?>>();

    List<Annotation> annotationsList = new ArrayList<Annotation>();
    if (visible != null) {
        annotationsList.addAll(Arrays.asList(visible.getAnnotations()));
    }
    if (invisible != null) {
        annotationsList.addAll(Arrays.asList(invisible.getAnnotations()));
    }

    for (Annotation nextAnnotation : annotationsList) {
        annotations.add(JAnnotation.getJAnnotation(nextAnnotation, this, getResolver()));
    }

    return annotations;
}
 
Example #19
Source File: JOperation.java    From jadira with Apache License 2.0 6 votes vote down vote up
@Override
public Set<JAnnotation<?>> getAnnotations() {

    AnnotationsAttribute visible = (AnnotationsAttribute) methodInfo.getAttribute(AnnotationsAttribute.visibleTag);
    AnnotationsAttribute invisible = (AnnotationsAttribute) methodInfo.getAttribute(AnnotationsAttribute.invisibleTag);

    Set<JAnnotation<?>> annotations = new HashSet<JAnnotation<?>>();

    List<Annotation> annotationsList = new ArrayList<Annotation>();
    if (visible != null) {
        annotationsList.addAll(Arrays.asList(visible.getAnnotations()));
    }
    if (invisible != null) {
        annotationsList.addAll(Arrays.asList(invisible.getAnnotations()));
    }

    for (Annotation nextAnnotation : annotationsList) {
        annotations.add(JAnnotation.getJAnnotation(nextAnnotation, this, getResolver()));
    }

    return annotations;
}
 
Example #20
Source File: JavassistUtilsTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
private void annotateField(
    final CtField ctfield,
    final String annotationName,
    final int annotationValue) {
  final AnnotationsAttribute attr =
      new AnnotationsAttribute(
          ctfield.getFieldInfo().getConstPool(),
          AnnotationsAttribute.visibleTag);
  final Annotation anno =
      new Annotation("java.lang.Integer", ctfield.getFieldInfo().getConstPool());
  anno.addMemberValue(
      annotationName,
      new IntegerMemberValue(ctfield.getFieldInfo().getConstPool(), annotationValue));
  attr.addAnnotation(anno);

  ctfield.getFieldInfo().addAttribute(attr);
}
 
Example #21
Source File: JavassistUtilsTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
private AnnotationsAttribute annotateMethod(
    final CtMethod ctmethod,
    final String annotationName,
    final int annotationValue) {
  final AnnotationsAttribute attr =
      new AnnotationsAttribute(
          ctmethod.getMethodInfo().getConstPool(),
          AnnotationsAttribute.visibleTag);
  final Annotation anno =
      new Annotation("java.lang.Integer", ctmethod.getMethodInfo().getConstPool());
  anno.addMemberValue(
      annotationName,
      new IntegerMemberValue(ctmethod.getMethodInfo().getConstPool(), annotationValue));
  attr.addAnnotation(anno);

  ctmethod.getMethodInfo().addAttribute(attr);

  return attr;
}
 
Example #22
Source File: JavassistUtilsTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateEmptyClass() {
  final CtClass emptyClass = JavassistUtils.generateEmptyClass();
  final CtClass anotherEmptyClass = JavassistUtils.generateEmptyClass();

  Assert.assertFalse(emptyClass.equals(anotherEmptyClass));

  // test empty class works as expected
  final CtMethod method = addNewMethod(emptyClass, "a");
  annotateMethod(method, "abc", 7);
  final CtField field = addNewField(emptyClass, "d");
  annotateField(field, "def", 9);

  Assert.assertEquals(
      7,
      ((IntegerMemberValue) ((AnnotationsAttribute) method.getMethodInfo().getAttribute(
          AnnotationsAttribute.visibleTag)).getAnnotation("java.lang.Integer").getMemberValue(
              "abc")).getValue());

  Assert.assertEquals(
      9,
      ((IntegerMemberValue) ((AnnotationsAttribute) field.getFieldInfo().getAttribute(
          AnnotationsAttribute.visibleTag)).getAnnotation("java.lang.Integer").getMemberValue(
              "def")).getValue());
}
 
Example #23
Source File: JavassistUtilsTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopyClassAnnontations() {
  final CtClass fromClass = ClassPool.getDefault().makeClass("fromClass");
  final CtClass toClass = ClassPool.getDefault().makeClass("toClass");

  // Create class annotations
  final ConstPool fromPool = fromClass.getClassFile().getConstPool();
  final AnnotationsAttribute attr =
      new AnnotationsAttribute(fromPool, AnnotationsAttribute.visibleTag);
  final Annotation anno = new Annotation("java.lang.Integer", fromPool);
  anno.addMemberValue("copyClassName", new IntegerMemberValue(fromPool, 246));
  attr.addAnnotation(anno);
  fromClass.getClassFile().addAttribute(attr);

  JavassistUtils.copyClassAnnotations(fromClass, toClass);

  final Annotation toAnno =
      ((AnnotationsAttribute) toClass.getClassFile().getAttribute(
          AnnotationsAttribute.visibleTag)).getAnnotation("java.lang.Integer");

  Assert.assertEquals(
      246,
      ((IntegerMemberValue) toAnno.getMemberValue("copyClassName")).getValue());
}
 
Example #24
Source File: JavassistUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * Simple helper method to take any FIELD targetable annotations from the method and copy them to
 * the new field. All JCommander annotations can target fields as well as methods, so this should
 * capture them all.
 */
public static void copyMethodAnnotationsToField(final CtMethod method, final CtField field) {
  // Load the existing annotations attributes
  final AnnotationsAttribute methodAnnotations =
      (AnnotationsAttribute) method.getMethodInfo().getAttribute(AnnotationsAttribute.visibleTag);

  // Clone them
  final AnnotationsAttribute copyMethodAttribute =
      JavassistUtils.cloneAnnotationsAttribute(
          field.getFieldInfo2().getConstPool(),
          methodAnnotations,
          ElementType.FIELD);

  // Set the annotations on the new class
  field.getFieldInfo().addAttribute(copyMethodAttribute);
}
 
Example #25
Source File: JavassistUtils.java    From statefulj with Apache License 2.0 6 votes vote down vote up
public static void addClassAnnotation(CtClass clazz, Class<?> annotationClass, Object... values) {
	ClassFile ccFile = clazz.getClassFile();
	ConstPool constPool = ccFile.getConstPool();
	AnnotationsAttribute attr = getAnnotationsAttribute(ccFile);
	Annotation annot = new Annotation(annotationClass.getName(), constPool);
	
	for(int i = 0; i < values.length; i = i + 2) {
		String valueName = (String)values[i];
		Object value = values[i+1];
		if (valueName != null && value != null) {
			MemberValue memberValue = createMemberValue(constPool, value);
			annot.addMemberValue(valueName, memberValue);
		}
	}
	
	attr.addAnnotation(annot);
}
 
Example #26
Source File: CamelBinder.java    From statefulj with Apache License 2.0 5 votes vote down vote up
private void addConsumeAnnotation(CtMethod ctMethod, String uri) {
	MethodInfo methodInfo = ctMethod.getMethodInfo();
	ConstPool constPool = methodInfo.getConstPool();

	Annotation consume = new Annotation(Consume.class.getName(), constPool);
	StringMemberValue valueVal = new StringMemberValue(constPool);
	valueVal.setValue(uri);
	consume.addMemberValue("uri", valueVal);

	AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
	attr.addAnnotation(consume);
	methodInfo.addAttribute(attr);
}
 
Example #27
Source File: JavassistUtils.java    From statefulj with Apache License 2.0 5 votes vote down vote up
public static void copyTypeAnnotations(Class<?> fromClass, CtClass toClass) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
	for(java.lang.annotation.Annotation annotation :  fromClass.getAnnotations()) {
		if (!StatefulController.class.isAssignableFrom(annotation.annotationType())) {
			ClassFile ccFile = toClass.getClassFile();
			AnnotationsAttribute attr = getAnnotationsAttribute(ccFile);
			Annotation clone = cloneAnnotation(ccFile.getConstPool(), annotation);
			attr.addAnnotation(clone);
		}
	}
}
 
Example #28
Source File: ByteCodeAnalyzer.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves all annotations of a package/class and its members (if requested).
 *
 * @param clazz        the <code>CtClass</code> to examine
 * @param elementTypes indicates which annotations to retrieve
 * @since 1.4
 */
@Nonnull
@SuppressWarnings("unchecked")
protected static Iterable<Annotation> getAnnotations(@Nonnull CtClass clazz, ElementType... elementTypes) {
    List<ElementType> types = asList(elementTypes);
    List<AttributeInfo> attributes = newArrayList();

    if (clazz.getName().endsWith("package-info") && types.contains(ElementType.PACKAGE) ||
            !clazz.getName().endsWith("package-info") && types.contains(ElementType.TYPE)) {
        attributes.addAll(clazz.getClassFile2().getAttributes());
    }
    if (types.contains(METHOD)) {
        for (CtMethod method : clazz.getDeclaredMethods()) {
            attributes.addAll(method.getMethodInfo2().getAttributes());
        }
    }
    if (types.contains(FIELD)) {
        for (CtField field : clazz.getDeclaredFields()) {
            attributes.addAll(field.getFieldInfo2().getAttributes());
        }
    }

    List<Annotation> annotations = newArrayList();
    for (AttributeInfo attribute : attributes) {
        if (AnnotationsAttribute.class.isInstance(attribute)) {
            Collections.addAll(annotations, AnnotationsAttribute.class.cast(attribute).getAnnotations());
        }
    }

    return annotations;
}
 
Example #29
Source File: JavassistUtils.java    From statefulj with Apache License 2.0 5 votes vote down vote up
public static void addResourceAnnotation(CtField field, String beanName) {
	FieldInfo fi = field.getFieldInfo();
	
	AnnotationsAttribute attr = new AnnotationsAttribute(
			field.getFieldInfo().getConstPool(), 
			AnnotationsAttribute.visibleTag);
	Annotation annot = new Annotation(Resource.class.getName(), fi.getConstPool());
	
	StringMemberValue nameValue = new StringMemberValue(fi.getConstPool());
	nameValue.setValue(beanName);
	annot.addMemberValue("name", nameValue);
	
	attr.addAnnotation(annot);
	fi.addAttribute(attr);
}
 
Example #30
Source File: ServiceDelegateBuilder.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addDelegateField(CtClass classBuilder) throws CannotCompileException {
    CtField field = CtField.make(String.format("%s service;", serviceClass.getCanonicalName()), classBuilder);
    AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
    attr.addAnnotation(annotation(new InjectImpl()));
    field.getFieldInfo().addAttribute(attr);
    classBuilder.addField(field);
}