Java Code Examples for javassist.bytecode.ClassFile#addAttribute()

The following examples show how to use javassist.bytecode.ClassFile#addAttribute() . 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: DefaultRepositoryGenerator.java    From business with Mozilla Public License 2.0 5 votes vote down vote up
Class<? extends T> generate(Class<? extends Repository> baseImpl) {
    try {
        CtClass cc = createClass(
                getClassName(baseImpl, getCounter(repositoryInterface).incrementAndGet()),
                baseImpl
        );
        ClassFile cf = cc.getClassFile();
        ConstPool constPool = cf.getConstPool();

        cc.setModifiers(Modifier.PUBLIC);

        cc.setInterfaces(new CtClass[]{classPool.getCtClass(repositoryInterface.getName())});

        if (hasGenericConstructor(baseImpl)) {
            cc.addConstructor(createConstructor(constPool, cc));
        } else {
            cc.addConstructor(createDefaultConstructor(cc));
        }

        cf.addAttribute(createQualifierAttribute(constPool, getQualifier(baseImpl)
                .orElseThrow(() -> new NotFoundException("Qualifier annotation not found"))));

        return cast(cc.toClass(
                classLoader,
                DefaultRepositoryCollector.class.getProtectionDomain())
        );
    } catch (CannotCompileException | NotFoundException e) {
        throw BusinessException.wrap(e, BusinessErrorCode.UNABLE_TO_CREATE_DEFAULT_IMPLEMENTATION)
                .put("interface", repositoryInterface)
                .put("base", baseImpl);
    }
}
 
Example 2
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);
	}
}