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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With