javassist创建类并添加方法

无聊,发现很多项目都有javassist这个包,做了个demo,创建一个临时类有时还挺有用的.

 

ClassPool cp = ClassPool.getDefault();
		try {
			CtClass cc = cp.makeClass("Tester");
			CtMethod cm = new CtMethod(CtClass.intType, "add", new CtClass[] {
					CtClass.intType, CtClass.intType }, cc);
			cm.setBody("return $1 + $2;");
			cm.insertAfter("for(int i=0;i<$args.length;i++)"
					+ "{System.out.println(\"args[\"+i+\"]=\"+$args[i]);}");
			cc.addMethod(cm);
			Class<?> c = cc.toClass();
			Object o = c.newInstance();
			Method m = c.getDeclaredMethod("add", int.class, int.class);
			System.out.println("Result:" + m.invoke(o, 1, 2));
		} catch (CannotCompileException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}

 

运行结果:

args[0]=1
args[1]=2
Result:3

你可能感兴趣的:(C++,c,C#)