简体   繁体   中英

Accessing protected class in java

I have an object represented as follows:

 public final class FooFunc<KEYIN extends WritableComparable, 
                            VALUEIN extends Writable, 
                            KEYOUT extends WritableComparable, 
                            VALUEOUT extends Writable> extends FooFunction<T<KEYIN,VALUEIN>,
                            T<KEYOUT,VALUEOUT>> implements Q<T<KEYOUT,VALUEOUT>>, S

 private transient Mapper<KEYIN,VALUEIN,KEYOUT,VALUEOUT> mapper; // main is this line
    ...
 }

I am working with mappers, whose information is available at: link

Mapper has some protected members (setup, cleanup and map methods) which I would like to access, but I am not able to access them. How should I design this in order to make sure that I can access those methods?

You can use Reflections to get access to these methods.
Have a look at Class.getDeclaredMethods() and AccessibleObject.setAccessible()

But if you need to do this your design is definitely wrong. The methods were hidden for a reason.


protected methods of a class can only be accessed by the subclasses of that class. I agree with Dawnkeeper that its most likely a design problem if you try to access protected methods with reflection. Their intended use is to allow subclasses to change specific party of the behaviour of their superclass (see eg the template method pattern: http://en.wikipedia.org/wiki/Template_method_pattern )

eg

public class Foo{
   public int getX() {return getProtectedX();}
   protected int getProtectedX() {return 42;}
}

public class Bar extends Foo{
   protected int getProtectedX() {return 43;}
}

public class runner{
public static void main()
    {
       Foo x=new Foo();
       System.out.println(x.getX()); // 42
       Bar y=new Bar();
       System.out.println(y.getX()); // 43
    }
}

Bye, Markus

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM