polymorphism - (Java) Is there a type of object that can handle anything from primitives to arrays? -
i'm pretty new java, i'm hoping 1 of guys knows how this. i'm having user specify both type , value of arguments, in xml-like way, passed methods external application.
example: javac myappsname externaljavaclass methodofexternalclass [parameters]
of course, find proper method, have have proper parameter types method may overloaded , that's way tell difference between different versions. parameters formatted in manner:
(type)value(/type), e.g. (int)71(/int) (string)this string i'm passing parameter!(/string)
i parse them, getting constructor whatever type indicated, execute constructor running method, newinstance(<string value>), loading new instance object. works fine , dandy, know, methods take arrays, or multi-dimensional arrays.
i handle argument formatting so: (array)(array)(int)0(/int)(int)1(/int)(/array)(array)(int)2(/int)(int)3(/int)(/array)(/array)... or perhaps better... {{(int)0(/int)(int)1(/int)}{(int)2(/int)(int)3(/int)}}.
the question is, how can implemented? have start wrapping in object[] array can handle primitives, etc. argobj[0], load array would? (unfortunately, have make object[][] array if wanted support two-dimensional arrays. implementation wouldn't pretty.)
i think looking here way dynamically call java methods based on attributes described inside xml file.
if that's case, can explore java reflection api.
example class:
package foo; public class bar { public void dosomething(string x) { system.out.println("this method dosomething takes in string parameter"); } public void dosomething(string [] arr, string str) { system.out.println("this method dosomething takes in string arr parameter , string parameter"); } } to dynamically use methods in class, following:
class c = class.forname("foo.bar"); object newinstance = c.newinstance(); method method = c.getmethod("dosomething", string.class); // locate first method method.invoke(newinstance, "hello world"); method method = c.getmethod("dosomething", string[].class, string.class); // locate second method string [] arr = {"hello", "world"}; method.invoke(newinstance, arr, "hello world"); so can specify in xml file follows:
<method> <name>dosomething</name> <params> <param>java.lang.string</param> </params> </method> <method> <name>dosomething</name> <params> <param>java.lang.string[]</param> // or other annotation indicate arr <param>java.lang.string</param> </params> </method> then, read xml file , use find java methods dynamically.
to dynamically create array:
class c = class.forname("java.lang.string"); int length = 5; object o = array.newinstance(c, length); // o string arr of length 5 string [] arr = (string []) o;
Comments
Post a Comment