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,

//Man.java

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

        public final String getMailPassword(){
            try{
                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){
                ex.printStackTrace();
            }
            return null;
        }
    }

//Boss.java

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

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

}

//Tester.java

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 (Tester.java) 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 Boss.java 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(Reflection.java:109)
    at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:261)
    at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:253)
    at java.lang.reflect.Method.invoke(Method.java:599)
    at com.test.Man.getMailPassword(Man.java:14)
    at com.test.Tester.main(Tester.java:8)
this: [email protected]
method: protected java.lang.String com.test.test2.Boss.getPassword()
null

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)

Answer

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

Leave a Reply

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