java - Better to use reflection or my little hack to access a private method? -


i need access private method class. have 2 ways of accessing it. first obvious reflection. second sort of hack. private method need call being called protected inner class's accessprivatemethod method. method literally call private method need. so, better access using reflection or better sort of "hack" extending protected inner class calls it. see code:

method = object.getclass().getdeclaredmethod("privatemethod"); method.setaccessible(true); object r = method.invoke(object); 

or: (protectedinnerclass protected inner class in class private method want access.)

class hack extends protectedinnerclass {     public void accessprivatemethod() {         // callprivatemethod literally calls private method         // need call.         super.callprivatemethod();     } } ... hack.accessprivatemethod(); 

some additional thoughts:

1) i've seen many people on here use reflection last resort.

2) reflection cause security issues? (securitymanager can deny setaccessible sometimes?) needs work time on machine/setup.

if hack isn't clear please , try elaborate more. thanks!

ps: private method need access in jung libraries. calling fixes bug. aka i'm trying find workaround without having edit of jung jars.

1) i've seen many people on here use reflection last resort.

assuming hack works, better use that, rather using reflection. because using reflection way more expensive.

here's extract on java's api concerning reflection:

  • because reflection involves types dynamically resolved, java virtual machine optimizations can not performed. consequently, reflective operations have slower performance non-reflective counterparts, , should avoided in sections of code called in performance-sensitive applications.

2) reflection cause security issues? (securitymanager can deny setaccessible sometimes?) needs work time on machine/setup.

likewise:

  • reflection requires runtime permission may not present when running under security manager. in important consideration code has run in restricted security context, such in applet.

so, not setaccessible method may denied, reflection usage overall.

another consideration in order call hack class method without instantiation, need set inner method static.

class hack extends protectedinnerclass {    public static void accessprivatemethod() {        super.callprivatemethod();    } } hack.accessprivatemethod(); 

Comments

Popular posts from this blog

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

wordpress - (T_ENDFOREACH) php error -

Using django-mptt to get only the categories that have items -