A Java object is not an instance of a declared class

public class SendEmailImpl 
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 example@example.com");
}

But I got wrong

Do you know where my code is wrong?

I've tried this too:

@Test
public void testValidEmail() throws NoSuchMethodException,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");
}

But the result is the same

Solution

You are using class < string > to call the isvalidemamailaddress method parameter (string. Class) instead of string In addition, the first parameter should be an instance of the class you want to call the method (because it is not a static method)

Reference method invoke Javadoc:

Correction code:

@Test
public void testValidEmail() throws NoSuchMethodException,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
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>