java - How to access unknown class methods -


i coding in java language, facing situation have

class a{ static class a1{     void same1(){}     int same2(){} } static class a2{ void same1(){}     int same2(){} } } 

i used generics store object in map, store description , objects a1 , a2

map<string, object> mapobject=new hashmap<string, object>(); 

is possible access methods inside inner classes if retrieve map classname. currently, able class name mapobject.get(key).getclass(). regarding highly appreciated.thank you.

see code see how work methods , invoking via reflections asked in comments. please note code adhoc , trying not seem right. hardly ever if @ 1 need call methods this. if in new question ask problem trying solve might see other better approaches.

package com.so;  import java.lang.reflect.invocationtargetexception; import java.lang.reflect.method; import java.util.hashmap; import java.util.map;  public class sample {     private map<string,foo> mapobject = new hashmap<string,foo>();      public sample(){         foo foo = new foo();         mapobject.put("key", foo);     }      public void callmethods() throws illegalaccessexception, illegalargumentexception, invocationtargetexception{         method[] methods = mapobject.get("key").getclass().getdeclaredmethods();         object objectstring = new string();         objectstring = "hello";         (method method : methods) {             if (method.getname().equalsignorecase("printthisstring")){                 method.invoke(mapobject.get("key"), objectstring)   ;             }           }      }      public static void main(string...args) throws illegalaccessexception, illegalargumentexception, invocationtargetexception{         sample sample = new sample();         sample.callmethods();     }  }  class foo {     public void printthisstring(string param){         system.out.println(param);     } } 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -