如何使用javassist实例化在运行时创建的类?

时间:2016-12-03 00:38:27

标签: java reflection javassist

我刚刚开始使用javassist而且我似乎无法弄清楚如何在运行时实例化一个类。

makeNewClass()方法使NewClass类成为:

public bin.objects.base.NewClass {
    public int quantity = 5;
    private float weight = 30.25f;

    public float getWeight() { return weight; }
    public void setWeight(float weight) { this.weight = weight; }
    public float totalWeight() { return quantity * getWeight(); }
}

这种方法很好用:

public void makeNewClass() throws NotFoundException, IOException, CannotCompileException {
        // ClassMaker maker holds the CtClass object and handles all the "making"
        ClassMaker maker = new ClassMaker("bin.objects.base.NewClass");

        maker.addField(CtClass.intType, "quantity", "5", Modifier.PUBLIC);
        maker.addField(CtClass.floatType, "weight", "30.25f", Modifier.PRIVATE);

        maker.addMethod(Modifier.PUBLIC, CtClass.floatType, "totalWeight", null, null, 
                "{ return quantity * getWeight(); }", null, MethodType.standard);
        maker.getCtClass().writeFile();
    }

现在开始出现问题。该方法应该实例化NewClass,访问它的字段,称之为方法。

    public void testNewClass() 
            throws Throwable {
        CtClass ctclass =  ClassPool.getDefault().get("bin.objects.base.NovaClasse");

        Object testClass = ctclass.toClass(new Loader(), null);

        // Throws NoSuchFieldException
        Field q = testClass.getClass().getDeclaredField("quantity");
        int quantity = (int) q.get(testClass);

        Class[] cArg = new Class[1];
        cArg[0] = Float.class;

        // Throws NoSuchMethodException
        Method m = testClass.getClass().getDeclaredMethod("getWeight", cArg);
        float weight = (float) m.invoke(testClass, null);

        // Throws NoSuchMethodException
        m = testClass.getClass().getDeclaredMethod("totalWeight", cArg);
        float totalWeight = (float) m.invoke(testClass, null);

        System.out.println("quantity = " + quantity +
                "weight = " + weight +
                "totalWeight = " + totalWeight);
    }

现在,我已经发现testClass实际上已初始化为java.lang.Class的实例,而不是bin.objects.base.NewClass。所以,显然,它不会找到NewClass的字段和方法。

问题是如何解决这个问题?我尝试使用java.lang.Class.cast()方法,但没有成功。

2 个答案:

答案 0 :(得分:2)

我终于能够找出问题所在。

显然,这是ClassLoader的一个问题。我找到了答案in this post。为了解决这个问题,我只是将这一行包括在内:

Class newClasse = ctclass.toClass(this.getClass().getClassLoader(), 
    this.getClass().getProtectionDomain());

@ nullpointer的回答也有帮助。

因此,经过一些更改后,testNewClass()方法最终结果如下:

public void testNewClass() 
            throws Throwable {
        CtClass ctclass =  ClassPool.getDefault().get("bin.objects.base.NewClass");
        Class newClass = ctclass.toClass(this.getClass().getClassLoader(), 
            this.getClass().getProtectionDomain());
        Object objNewClass  = newClass.newInstance();

        System.out.println("Accessing the field 'public int quantity'..."); 
        Field q = newClass.getDeclaredField("quantity");        
        int quantity = (int) q.get(objNewClass);
        System.out.println("quantity = " + quantity);

        System.out.println("\nAccessing the field 'private float weight' " +
            "through the method 'public float getWeight()'...");
        Method m = newClass.getDeclaredMethod("getWeight", null);
        float weight = (float) m.invoke(objNewClass, null);
        System.out.println("weight = " + weight);

        System.out.println("\nAccessing the method 'public float totalWeight()'...");
        m = newClass.getDeclaredMethod("totalWeight", null);
        float totalWeight = (float) m.invoke(objNewClass, null);        
        System.out.println("totalWeight = " + totalWeight);
    }

答案 1 :(得分:0)

尝试使用反射将您的类对象作为:

Field q = Class.forName("bin.objetos.base.NovaClasse").getDeclaredField("quantity");

您也可以对其他字段执行相同的操作。