Java对象不是声明类的实例

时间:2015-11-02 11:13:43

标签: java reflection

public class SendEmailImpl 
{     
    private boolean isValidEmailAddress(String email)
    {
        boolean stricterFilter = true;
        String stricterFilterString = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        String laxString = ".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
        String emailRegex = stricterFilter ? stricterFilterString : laxString;
        Pattern p = Pattern.compile(emailRegex);
        Matcher m = p.matcher(email);
        return m.matches();
    } 
}

我尝试使用反射

调用此代码
@Test
public void testValidEmail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
    Method method = SendEmailImpl.class.getDeclaredMethod("isValidEmailAddress", String.class);
    method.setAccessible(true);
    Boolean invoke = (Boolean) method.invoke("isValidEmailAddress", String.class);

    assertTrue(invoke);
    System.out.println("Testing E-mail validator - case example@example.com");
}

但我收到错误

  

java.lang.IllegalArgumentException:object不是声明类的实例

你知道我的代码在哪里错了吗?

我也试过这个:

@Test
public void testValidEmail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
    Method method1 = SendEmailImpl.class.getDeclaredMethod("isValidEmailAddress", String.class);
    method1.setAccessible(true);

    Boolean invoke = (Boolean)method1.invoke(String.class);
    assertTrue(invoke);
    System.out.println("Testing E-mail validator - case example@example.com");
}

但结果是一样的。

1 个答案:

答案 0 :(得分:7)

您正在使用isValidEmailAddress参数(Class<String>)而不是String.class调用String方法。此外,第一个参数应该是您要调用方法的类的实例(因为它不是静态方法)。

引用Method.invoke Javadoc:

  

<强>参数

     
      
  • obj - 从
  • 调用基础方法的对象   
  • args - 用于方法调用的参数
  •   

更正后的代码:

@Test
public void testValidEmail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    SendEmailImpl instance = new SendEmailImpl();
    Method method = instance.getClass().getDeclaredMethod("isValidEmailAddress", String.class);
    method.setAccessible(true);
    Boolean invoke = (Boolean) method.invoke(instance, "myStringArgument");
    // rest of code
}