Method invocation fails when class from other package

I am trying to write base code for my program, where I want to make some authentication check before returning some information.

Here is a sample code of it,


package com.test;
import java.lang.reflect.Method;
    public abstract class Man {
        protected abstract String getPassword();

        public final String getMailPassword(){
                Method method = getClass().getDeclaredMethod("getPassword");
                System.out.println("this: " + this);
                System.out.println("method: "+ method.toString());          
                //check something if all OK
                return (String)method.invoke(this);
                //else return null
            }catch(Exception ex){
            return null;


package com.test;
import com.test.Man;

public class Boss extends Man {
    protected String getPassword() {
        return "Boss'_password";



package com.test;
import com.test.test2.Boss;
public class Tester {
    public static void main(String arg[]){
        //System.out.println(new Servent().getMailPassword());      
        System.out.println(new Boss().getMailPassword());

When I execute above code ( It execute correctly (all the files in same package), and I get following output.

this: [email protected]
method: protected java.lang.String
com.test.Boss.getPassword() Boss'_password

But If I move then to different package “test2”, I get exception.

java.lang.IllegalAccessException: Class com.test.Man can not access a member of class com.test.test2.Boss with modifiers "protected"
    at sun.reflect.Reflection.ensureMemberAccess(
    at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(
    at java.lang.reflect.AccessibleObject.checkAccess(
    at java.lang.reflect.Method.invoke(
    at com.test.Man.getMailPassword(
    at com.test.Tester.main(
this: [email protected]
method: protected java.lang.String com.test.test2.Boss.getPassword()

I have printed ‘this’ which gives this: [email protected], but the exception detects the super class in this case Class com.test.Man can not access a member of class com.test.test2.Boss with modifiers "protected". I understood the exception, but I didn’t understood why in second case it detected super class. Please if some one can help me to fix this out (I have need of having sub classes in different packages, I can’t put them in same package)


Call method.setAccessible(true) before calling invoke()

Leave a Reply

Your email address will not be published. Required fields are marked *