Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object is not an instance of declaring class

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();
    } 
}

I tried to call this code using reflection

@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 [email protected]");
}

But I get error

java.lang.IllegalArgumentException: object is not an instance of declaring class

Do you have any idea where is my code wrong?

I also tried this:

@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 [email protected]");
}

But the result is the same.

like image 873
Peter Penzov Avatar asked Nov 02 '15 11:11

Peter Penzov


1 Answers

You are invoking the isValidEmailAddress method with a Class<String> parameter (String.class) instead of a String. Also, the first argument should be an instance of the class you want to invoke the method on (since it is not a static method).

Quoting Method.invoke Javadoc:

Parameters:

  • obj - the object the underlying method is invoked from
  • args - the arguments used for the method call

Corrected code:

@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
}
like image 141
Tunaki Avatar answered Nov 15 '22 10:11

Tunaki