using JAVA reflection to execute the class -



using JAVA reflection to execute the class -

so, here class private inner class declared within , private attribute. need utilize java reflection writing test programme in main function execute class.

public class outter { private inner in; public outter(){ in = new inner(); } private class inner{ private void test(){ system.out.println("test"); } }

}

here test code: my questions listed next statement.

public class test { public static void main(string[] args) throws exception { // 1. how create class type inner class since modifier // private, if going need .setaccessible() how // utilize it? class outter1 = outter.class; // 2. how pass parameters of type inner class object? constructor con = outter1.getconstructor(new class[]{int.class}); // 3. this? field fields = outter1.getfield("test"); fields.setaccessible(true); // 4. lost logic route me follow when // using java reflection execute class this! object temp = outter1.newinstance(); outter outter = (outter)temp; system.out.println(fields.get(outter)); } }

here's self-contained illustration of you're trying do.

code you're running

try { // gets "in" field field f = outer.class.getdeclaredfield("in"); // sets accessible it's private f.setaccessible(true); // gets instance of inner class getting instance of // "in" field instance of outer class - know "in" // initialized in no-args constructor object o = object o = f.get(outer.class.newinstance()); // gets "execute" method method m = o.getclass().getdeclaredmethod("test", (class<?>[])null); // sets accessible context m.setaccessible(true); // invokes method m.invoke(o, (object[])null); } // todo improve handling grab (throwable t) { t.printstacktrace(); }

classes (inner/outer)...

public class outer { private inner in; public outer() { in = new inner(); } private class inner { private void test() { system.out.println("test"); } } }

output

test

java reflection

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -