2012-11-07 42 views
0

我无法弄清楚我做错了什么。我有2种方法,这其中一个作品:反射调用跳过代码的其余部分

protected void applySelection(String adjustment, String action){ 
    if(!adjustment.equals("") || !action.equals("")){ 
     try{ 
      ClassLoader myClassLoader = this.getClass().getClassLoader(); 
      String myPackage = this.getClass().getPackage().getName(); 
      String classNameToBeLoaded = myPackage + "." + action + "." + adjustment; 
      Class adjust = myClassLoader.loadClass(classNameToBeLoaded); 
      Object whatInstance = adjust.newInstance(); 
      adjust.getMethod("setBitmap", new Class[]{Bitmap.class}).invoke(whatInstance, new Object[]{this.stage.getImage()}); 
      Bitmap bmp = (Bitmap)adjust.getMethod("applyFilter").invoke(whatInstance); 
      if(bmp != null){ 
       Edit.this.stage.setStageImage(bmp); 
       Edit.this.stage.showTopItems(bmp); 
      } 
     }catch(IllegalArgumentException e){ 
     }catch(IllegalAccessException e){ 
     }catch(InvocationTargetException e){ 
     }catch(Exception e){} 
    } 
} 



那么这一个不工作:

protected void setFromSlider(String adjustment, String action){ 
    if(!adjustment.equals("") || !action.equals("")){ 
     try{ 
      ClassLoader myClassLoader = this.getClass().getClassLoader(); 
      String myPackage = this.getClass().getPackage().getName(); 
      String classNameToBeLoaded = myPackage + "." + action + "." + adjustment; 
      Class adjust = myClassLoader.loadClass(classNameToBeLoaded); 
      Object whatInstance = adjust.newInstance(); 
      Object returnVal = adjust.getMethod("isSeekBar").invoke(whatInstance); 
      if(returnVal == true){ 
       // Do something 
      }else{ 
       // Do something else 
      } 
     }catch(NullPointerException e){ 
      e.getMessage(); 
     }catch(IllegalArgumentException e){ 
      e.getMessage(); 
     }catch(IllegalAccessException e){ 
      e.getMessage(); 
     }catch(Exception e){ 
      e.getMessage(); 
     } 
    } 
} 

在这条线(在第二个方法):
Object returnVal = adjust.getMethod("isSeekBar").invoke(whatInstance);

当它到达这里时,它只是跳过我的if语句并直接进入方法的右大括号。是什么原因造成的?这里是被调用的方法:

public boolean isSeekBar(){ 
    return true; 
} 

我假设它是抛出一个错误,但没有捕获语句捕捉一个。我现在难倒了...

+0

可能会出现一些异常出现? – kosa

+0

在你的'catch'块中,你正在检索异常消息并且什么也不做。尝试将消息记录到'System.err' –

+0

对于每个catch语句,我做了System.err.append(e.getMessage());并没有任何内容被发送到错误控制台。 –

回答

0

您可以尝试捕获更通用的Throwable - 如果此功能在UI线程中执行,您将看不到异常。

try{ 
    ... 
}catch(Throwable e){ 
    // e.getMessage(); this would not print anything 
    e.printStackTrace(); 
} 

在任何情况下,if(returnVal == true){不编译(数不兼容对象类型和布尔)

使用if (returnVal.equals(true)) {

+0

谢谢!修复了不兼容问题,但仍未解决原始问题。什么是通用Throwable?我对Java仍然很陌生。 –

+0

我编辑了我的答案以澄清。顺便说一句,我运行你的代码,它适用于我。另外,'e.getMessage()'不会打印任何东西 – thedayofcondor

+0

你的权利,它确实有效。我重新启动了Netbeans,代码突然开始以我期望的方式工作。 –

相关问题