Java Code Examples for javassist.bytecode.AnnotationsAttribute#visibleTag()

The following examples show how to use javassist.bytecode.AnnotationsAttribute#visibleTag() . 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: 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 2
Source File: JavassistUtils.java    From statefulj with Apache License 2.0 6 votes vote down vote up
public static void addMethodAnnotations(CtMethod ctMethod, Method method) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
	if (method != null) {
		MethodInfo methodInfo = ctMethod.getMethodInfo();
		ConstPool constPool = methodInfo.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		methodInfo.addAttribute(attr);
		for(java.lang.annotation.Annotation anno : method.getAnnotations()) {

			// If it's a Transition skip
			// TODO : Make this a parameterized set of Filters instead of hardcoding
			//
			Annotation clone = null;
			if (anno instanceof Transitions || anno instanceof Transition) {
				// skip
			} else {
				clone = cloneAnnotation(constPool, anno);
				attr.addAnnotation(clone);
			}
		}
	}
}
 
Example 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
Source File: ClassVisitor.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the given annotations to the given field. Can be used to avoid problems with OR mappers by adding
 * an annotation "javax.persistence.Transient".
 * @param _fld
 * @param _annotations
 */
private void addFieldAnnotations(CtField _fld, String[] _annotations) {
	if(_annotations!=null && _annotations.length>0) {
		final ConstPool cpool = this.c.getClassFile().getConstPool();
		final AnnotationsAttribute attr = new AnnotationsAttribute(cpool, AnnotationsAttribute.visibleTag);
		for(String anno: _annotations) {
			final Annotation annot = new Annotation(anno, cpool);
			attr.addAnnotation(annot);
		}
		_fld.getFieldInfo().addAttribute(attr);
	}
}
 
Example 11
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);
}
 
Example 12
Source File: ModelInstrumentation.java    From javalite with Apache License 2.0 5 votes vote down vote up
private void addGeneratedAnnotation(CtMethod generatedMethod, CtClass target)
{
    ConstPool constPool = target.getClassFile().getConstPool();
    AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);

    Annotation annot = new Annotation("javax.annotation.Generated", constPool);
    annot.addMemberValue("value", new StringMemberValue("org.javalite.instrumentation.ModelInstrumentation", constPool));

    ZonedDateTime now = ZonedDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(GENERATED_DATE_PATTERN);
    annot.addMemberValue("date", new StringMemberValue(now.format(formatter), constPool));

    attr.addAnnotation(annot);
    generatedMethod.getMethodInfo().addAttribute(attr);
}
 
Example 13
Source File: SwaggerMoreDoclet.java    From swagger-more with Apache License 2.0 5 votes vote down vote up
private static AnnotationsAttribute getAnnotationAttr(CtMethod ctMethod) {
    for (Object o : ctMethod.getMethodInfo().getAttributes()) {
        if (o instanceof AnnotationsAttribute) {
            return (AnnotationsAttribute) o;
        }
    }
    return new AnnotationsAttribute(ctMethod.getMethodInfo().getConstPool(), AnnotationsAttribute.visibleTag);
}
 
Example 14
Source File: SwaggerMoreDoclet.java    From swagger-more with Apache License 2.0 5 votes vote down vote up
private static AnnotationsAttribute getAnnotationAttr(CtClass ctClass) {
    for (Object o : ctClass.getClassFile().getAttributes()) {
        if (o instanceof AnnotationsAttribute) {
            return (AnnotationsAttribute) o;
        }
    }
    return new AnnotationsAttribute(ctClass.getClassFile().getConstPool(), AnnotationsAttribute.visibleTag);
}
 
Example 15
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 16
Source File: AbstractJavassistConfigurationInstanceCreator.java    From conf4j with MIT License 4 votes vote down vote up
protected void addInternalAnnotation(CtMethod ctMethod) {
    ConstPool constPool = ctClass.getClassFile().getConstPool();
    AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
    attr.setAnnotations(new Annotation[]{new Annotation(Internal.class.getName(), constPool)});
    ctMethod.getMethodInfo().addAttribute(attr);
}
 
Example 17
Source File: AsmRest.java    From fastquery with Apache License 2.0 4 votes vote down vote up
/**
 * 自动生成Repository接口的实现类并以字节的形式返回.
 * 
 * @param repositoryClazz repository class
 * @return 生成的类字节码
 */
public static byte[] generateBytes(Class<?> repositoryClazz) {

	// 生成类
	ClassPool pool = ClassPool.getDefault();
	// web容器中的repository 需要增加classPath
	ClassClassPath classClassPath = new ClassClassPath(repositoryClazz);
	pool.removeClassPath(classClassPath);
	pool.insertClassPath(classClassPath);
	String className = repositoryClazz.getName() + Placeholder.REST_SUF;
	CtClass ctClass = pool.makeClass(className);

	ClassFile ccFile = ctClass.getClassFile();
	ConstPool constpool = ccFile.getConstPool();

	try {
		// 增加接口
		ctClass.setInterfaces(new CtClass[] { pool.get(repositoryClazz.getName()) });

		// 增加字段
		CtClass executor = pool.get(repositoryClazz.getName());
		CtField field = new CtField(executor, "d", ctClass);
		field.setModifiers(Modifier.PRIVATE);
		FieldInfo fieldInfo = field.getFieldInfo();
		// 标识属性注解
		AnnotationsAttribute fieldAttr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
		javassist.bytecode.annotation.Annotation autowired = new javassist.bytecode.annotation.Annotation(
				"javax.inject.Inject", constpool);
		fieldAttr.addAnnotation(autowired);
		fieldInfo.addAttribute(fieldAttr);
		ctClass.addField(field);
		
		AsmRepository.addGetInterfaceClassMethod(repositoryClazz, ctClass);
		
		// 标识类注解
		AnnotationsAttribute classAttr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
		javassist.bytecode.annotation.Annotation singAnn = new javassist.bytecode.annotation.Annotation(
				"javax.inject.Singleton", constpool);
		classAttr.addAnnotation(singAnn);
		ccFile.addAttribute(classAttr);

		// 实现抽象方法
		Method[] methods = repositoryClazz.getMethods();
		for (Method method : methods) {
			if (!method.isDefault()) {
				CtMethod cm = CtMethod.make(AsmRepository.getMethodDef(method) + "{return d."+method.getName()+"($$);}", ctClass);
				// 标识方法注解
				AnnotationsAttribute methodAttr = new AnnotationsAttribute(constpool,
						AnnotationsAttribute.visibleTag);
				javassist.bytecode.annotation.Annotation extendsAnn = new javassist.bytecode.annotation.Annotation(
						"org.fastquery.core.Extends", constpool);
				ArrayMemberValue arrayMemberValue = new ArrayMemberValue(constpool);
				Annotation[] mas = method.getAnnotations();
				ClassMemberValue[] cmvs = new ClassMemberValue[mas.length];
				for (int i = 0; i < mas.length; i++) {
					cmvs[i] = new ClassMemberValue(mas[i].annotationType().getName(), constpool);
				}
				arrayMemberValue.setValue(cmvs);
				extendsAnn.addMemberValue("value", arrayMemberValue);
				methodAttr.addAnnotation(extendsAnn);
				MethodInfo info = cm.getMethodInfo();
				info.addAttribute(methodAttr);
				ctClass.addMethod(cm);
			}
		}
		
		return ctClass.toBytecode();

	} catch (Exception e) {
		throw new ExceptionInInitializerError(e);
	}
}
 
Example 18
Source File: JavassistUtils.java    From geowave with Apache License 2.0 4 votes vote down vote up
/**
 * This function will take the given annotations attribute and create a new attribute, cloning all
 * the annotations and specified values within the attribute. The annotations attribute can then
 * be set on a method, class, or field.
 */
public static AnnotationsAttribute cloneAnnotationsAttribute(
    final ConstPool constPool,
    final AnnotationsAttribute attr,
    final ElementType validElementType) {

  // We can use system class loader here because the annotations for
  // Target
  // are part of the Java System.
  final ClassLoader cl = ClassLoader.getSystemClassLoader();

  final AnnotationsAttribute attrNew =
      new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);

  if (attr != null) {
    for (final Annotation annotation : attr.getAnnotations()) {
      final Annotation newAnnotation = new Annotation(annotation.getTypeName(), constPool);

      // If this must target a certain type of field, then ensure we
      // only
      // copy over annotations that can target that type of field.
      // For instances, a METHOD annotation can't be applied to a
      // FIELD or TYPE.
      Class<?> annoClass;
      try {
        annoClass = cl.loadClass(annotation.getTypeName());
        final Target target = annoClass.getAnnotation(Target.class);
        if ((target != null) && !Arrays.asList(target.value()).contains(validElementType)) {
          continue;
        }
      } catch (final ClassNotFoundException e) {
        // Cannot apply this annotation because its type cannot be
        // found.
        LOGGER.error("Cannot apply this annotation because it's type cannot be found", e);
        continue;
      }

      // Copy over the options for this annotation. For example:
      // @Parameter(names = "-blah")
      // For this, a member value would be "names" which would be a
      // StringMemberValue
      if (annotation.getMemberNames() != null) {
        for (final Object memberName : annotation.getMemberNames()) {
          final MemberValue memberValue = annotation.getMemberValue((String) memberName);
          if (memberValue != null) {
            newAnnotation.addMemberValue((String) memberName, memberValue);
          }
        }
      }
      attrNew.addAnnotation(newAnnotation);
    }
  }
  return attrNew;
}
 
Example 19
Source File: DefaultRepositoryGenerator.java    From business with Mozilla Public License 2.0 4 votes vote down vote up
private AnnotationsAttribute createQualifierAttribute(ConstPool constPool,
        java.lang.annotation.Annotation qualifier) throws NotFoundException {
    AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
    attr.setAnnotation(copyAnnotation(constPool, qualifier));
    return attr;
}
 
Example 20
Source File: DefaultRepositoryGenerator.java    From business with Mozilla Public License 2.0 4 votes vote down vote up
private void addInjectAnnotation(ConstPool constPool, CtConstructor cc) {
    AnnotationsAttribute attribute = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
    attribute.setAnnotation(createAnnotation(constPool, Inject.class));
    cc.getMethodInfo().addAttribute(attribute);
}