Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Dynamic Invocation

50% developed
From Wikibooks, open books for an open world
<Java Programming |Reflection

NavigateReflection topic:()

We start with basic transfer object:

Computer codeCode listing 10.1: DummyTo.java
packagecom.test;publicclassDummyTo{privateStringname;privateStringaddress;publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicStringgetAddress(){returnaddress;}publicvoidsetAddress(Stringaddress){this.address=address;}publicDummyTo(Stringname,Stringaddress){this.name=name;this.address=address;}publicDummyTo(){this.name=newString();this.address=newString();}publicStringtoString(StringappendBefore){returnappendBefore+" "+name+", "+address;}}

Following is the example for invoking method from the above mentioned to dynamically.Code is self explanatory.

Computer codeCode listing 10.2: ReflectTest.java
packagecom.test;importjava.lang.reflect.Constructor;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;publicclassReflectTest{publicstaticvoidmain(String[]args){try{Class<?>dummyClass=Class.forName("com.test.DummyTo");// parameter types for methodsClass<?>[]partypes=newClass[]{String.class};// Create method object. methodname and parameter typesMethodmeth=dummyClass.getMethod("toString",partypes);// parameter types for constructorClass<?>[]constrpartypes=newClass[]{String.class,String.class};//Create constructor object. parameter typesConstructor<?>constr=dummyClass.getConstructor(constrpartypes);// create instanceObjectdummyto=constr.newInstance(newObject[]{"Java Programmer","India"});// Arguments to be passed into methodObject[]arglist=newObject[]{"I am"};// invoke method!!Stringoutput=(String)meth.invoke(dummyto,arglist);System.out.println(output);}catch(ClassNotFoundExceptione){e.printStackTrace();}catch(SecurityExceptione){e.printStackTrace();}catch(NoSuchMethodExceptione){e.printStackTrace();}catch(IllegalArgumentExceptione){e.printStackTrace();}catch(IllegalAccessExceptione){e.printStackTrace();}catch(InvocationTargetExceptione){e.printStackTrace();}catch(InstantiationExceptione){e.printStackTrace();}}}
Standard input or outputConsole for Code listing 10.2
I am Java Programmer, India

Conclusion: Above examples demonstrate the invocation of method dynamically using reflection.


Clipboard

To do:
Add some exercises like the ones inVariables

Retrieved from "https://en.wikibooks.org/w/index.php?title=Java_Programming/Reflection/Dynamic_Invocation&oldid=3644577"
Category:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp