反射java.lang.ClassNotFoundException

时间:2012-11-06 21:00:35

标签: java android

我使用以下内容:

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode){
        case EDIT_ADJUSTMENT:
            if(resultCode == RESULT_OK){
                try{
                    String adjustment = data.getStringExtra("adjustment");
                    adjustment = adjustment.replace(" ", "");
                    ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
                    String classNameToBeLoaded = "com.picpic.adjustments." + adjustment;
                    Class adjust = myClassLoader.loadClass(classNameToBeLoaded);
                }catch(Exception e){
                    String msg = e.getMessage();
                }
            }
        break;
    }
}

当它到达Class adjust = myClassLoader.loadClass(classNameToBeLoaded);时,我得到以下例外:java.lang.ClassNotFoundException: com.picpic.adjustments.ColorCorrect

ColorCorrect的包裹是com.picpic.adjustments

那么,为什么会抛出这个错误?如果您需要更多信息,请与我们联系。谢谢!

2 个答案:

答案 0 :(得分:3)

我猜这是因为您正在尝试加载类的类加载器看不到您的类。

我建议您尝试使用this.getClass().getClassLoader()代替ClassLoader.getSystemClassLoader()

Java有一个ClassLoader层次结构。每个类加载器都有不同的类路径来加载类。由于您尝试加载的类似乎是用户定义的类,因此ClassLoader.getSystemClassLoader()方法返回的类加载器可能看不到它。 (您可以尝试使用Google搜索Java ClassLoader层次结构。如果您之前不了解此问题,可能这个link很有用。)。

答案 1 :(得分:0)

这是我用来解决问题的代码:

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode){
        case EDIT_ADJUSTMENT:
            if(resultCode == RESULT_OK){
                String adjustment = data.getStringExtra("adjustment");
                adjustment = adjustment.replace(" ", "");
                try{
                    ClassLoader myClassLoader = Edit.this.getClass().getClassLoader();
                    String myPackage = Edit.this.getClass().getPackage().getName();
                    String classNameToBeLoaded = myPackage + ".adjustments." + adjustment;
                    Class adjust = myClassLoader.loadClass(classNameToBeLoaded);
                    Object whatInstance = adjust.newInstance();
                    adjust.getMethod("setBitmap", new Class[]{Bitmap.class}).invoke(whatInstance, new Object[]{Edit.this.stage.getImage()});
                    Bitmap bmp = (Bitmap)adjust.getMethod("applyFilter").invoke(whatInstance);
                    Edit.this.stage.setStageImage(bmp);
                    Edit.this.stage.showTopItems(bmp);
                }catch(Exception e){
                    String msg = e.getMessage();
                }
            }
            break;
    }
}