javassist.bytecode.DuplicateMemberException Java Examples

The following examples show how to use javassist.bytecode.DuplicateMemberException. 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: 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 #2
Source File: AddMethods.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
private static void addGetter(CtClass clazz, String pname, String paramType, String getPropertyMethod) throws Exception {
    String mname = "get" + pname.substring(0, 1).toUpperCase() + pname.substring(1);
    String mbody = "public " + paramType + " " + mname + "() throws java.sql.SQLException { return " + getPropertyMethod + "(\"" + pname + "\");}";
    System.out.println(mbody);
    try {
        CtMethod m = CtNewMethod.make(mbody, clazz);
        clazz.addMethod(m);
        System.out.println(m);
    } catch (DuplicateMemberException ex) {
        // ignore
    }
}
 
Example #3
Source File: AddMethods.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
private static void addSetter(CtClass clazz, String pname, String paramType, String setPropertyMethod) throws Exception {
    String mname = "set" + pname.substring(0, 1).toUpperCase() + pname.substring(1);
    String mbody = "public void " + mname + "(" + paramType + " value) throws java.sql.SQLException { " + setPropertyMethod + "(\"" + pname
            + "\", value);}";
    System.out.println(mbody);
    try {
        CtMethod m = CtNewMethod.make(mbody, clazz);
        clazz.addMethod(m);
        System.out.println(m);
    } catch (DuplicateMemberException ex) {
        // ignore
    }
}
 
Example #4
Source File: MethodBuilder.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Override
public CodeBuilder end() {
	code("}");
	CtClass cc = cm.getDeclaringClass();
	String body = toString();
	try {
		int mod = cm.getModifiers();
		mod = Modifier.clear(mod, Modifier.ABSTRACT);
		mod = Modifier.clear(mod, Modifier.NATIVE);
		cm.setModifiers(mod);
		cm.setBody(body);
		try {
			cc.addMethod(cm);
		} catch (DuplicateMemberException ignored) {
			// ignore
		}
		if (logger.isTraceEnabled()) {
			logger.trace(
					"public {} {}({}) {{}}",
					new Object[] { cm.getReturnType().getName(),
							cm.getName(), cm.getParameterTypes(), body });
		}
	} catch (Exception e) {
		StringBuilder sb = new StringBuilder();
		try {
			for (CtClass inter : cc.getInterfaces()) {
				sb.append(inter.getSimpleName()).append(" ");
			}
		} catch (NotFoundException e2) {
		}
		String sn = cc.getSimpleName();
		System.err.println(sn + " implements " + sb);
		throw new ObjectCompositionException(e.getMessage() + " for "
				+ body, e);
	}
	clear();
	return this;
}
 
Example #5
Source File: Patcher.java    From ModTheSpire with MIT License 4 votes vote down vote up
public static void patchEnums(ClassLoader loader, ClassPool pool, URL... urls)
    throws IOException, ClassNotFoundException, NotFoundException, CannotCompileException
{
    AnnotationDB db = new AnnotationDB();
    db.setScanClassAnnotations(false);
    db.setScanMethodAnnotations(false);
    db.scanArchives(urls);

    Set<String> annotations = db.getAnnotationIndex().get(SpireEnum.class.getName());
    if (annotations == null) {
        return;
    }

    boolean hasPrintedWarning = false;

    for (String s : annotations) {
        Class<?> cls = loader.loadClass(s);
        for (Field field : cls.getDeclaredFields()) {
            SpireEnum spireEnum = field.getDeclaredAnnotation(SpireEnum.class);
            if (spireEnum != null) {
                String enumName = field.getName();
                if (!spireEnum.name().isEmpty()) {
                    enumName = spireEnum.name();
                }

                // Patch new field onto the enum
                try {
                    CtClass ctClass = pool.get(field.getType().getName());
                    CtField f = new CtField(ctClass, enumName, ctClass);
                    f.setModifiers(Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL | Modifier.ENUM);
                    ctClass.addField(f);
                } catch (DuplicateMemberException ignore) {
                    // Field already exists
                    if (!Loader.DEBUG && !hasPrintedWarning) {
                        hasPrintedWarning = true;
                        System.out.println();
                    }
                    System.out.println(String.format("Warning: @SpireEnum %s %s is already defined.", field.getType().getName(), enumName));
                }
            }
        }
    }
}
 
Example #6
Source File: JavassistProxy.java    From gadtry with Apache License 2.0 4 votes vote down vote up
private static Class<?> createProxyClass(String basePackage, ProxyRequest<?> request)
        throws Exception
{
    Class<?> superclass = request.getSuperclass();
    ClassPool classPool = new ClassPool(true);
    classPool.appendClassPath(new LoaderClassPath(request.getClassLoader()));

    // New Create Proxy Class
    CtClass proxyClass = classPool.makeClass(basePackage + ".$JvstProxy" + number.getAndIncrement() + "$" + superclass.getSimpleName());
    CtClass parentClass = classPool.get(superclass.getName());
    final List<CtClass> ctInterfaces = MutableList.of(parentClass);

    // 添加继承父类
    if (superclass.isInterface()) {
        proxyClass.addInterface(parentClass);
    }
    else {
        checkState(!java.lang.reflect.Modifier.isFinal(superclass.getModifiers()), superclass + " is final");
        proxyClass.setSuperclass(parentClass);
    }

    for (Class<?> it : request.getInterfaces()) {
        if (it == ProxyHandler.class || it.isAssignableFrom(superclass)) {
            continue;
        }
        CtClass ctClass = classPool.get(it.getName());
        checkState(ctClass.isInterface(), ctClass.getName() + " not is Interface");

        ctInterfaces.add(ctClass);
        proxyClass.addInterface(ctClass);
    }

    //和jdk java.lang.reflect.Proxy.getProxyClass 创建代理类保持行为一致,生成的代理类自动继承Serializable接口
    if (!proxyClass.subtypeOf(classPool.get(Serializable.class.getName()))) {
        proxyClass.addInterface(classPool.get(Serializable.class.getName()));
    }

    //check duplicate class
    for (Map.Entry<CtClass, List<CtClass>> entry : ctInterfaces.stream().collect(Collectors.groupingBy(k -> k)).entrySet()) {
        if (entry.getValue().size() > 1) {
            throw new DuplicateMemberException("duplicate class " + entry.getKey().getName());
        }
    }

    // 添加 ProxyHandler 接口
    installProxyHandlerInterface(classPool, proxyClass);

    // 添加方法和字段
    installFieldAndMethod(proxyClass, ctInterfaces, request);

    // 设置代理类的类修饰符
    proxyClass.setModifiers(Modifier.PUBLIC | Modifier.FINAL);

    //-- 添加构造器
    if (superclass.getConstructors().length == 0) {
        addVoidConstructor(proxyClass);  //如果没有 任何非私有构造器,则添加一个
    }

    // 持久化class到硬盘, 可以直接反编译查看
    //proxyClass.writeFile("out/.");
    return proxyClass.toClass(request.getClassLoader(), superclass.getProtectionDomain());
}