Jump to content
Wikibooks The Free Textbook Project

Dynamic Invocation

From Wikibooks, open books for an open world
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

We start with basic transfer object:

Computer code Code listing 10.1: DummyTo.java
packagecom.test;

publicclass DummyTo{
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 code Code listing 10.2: ReflectTest.java
packagecom.test;

importjava.lang.reflect.Constructor;
importjava.lang.reflect.InvocationTargetException;
importjava.lang.reflect.Method;

publicclass ReflectTest{
publicstaticvoidmain(String[]args){
try{
Class<?>dummyClass=Class.forName("com.test.DummyTo");

// parameter types for methods
Class<?>[]partypes=newClass[]{String.class};

// Create method object. methodname and parameter types
Methodmeth=dummyClass.getMethod("toString",partypes);

// parameter types for constructor
Class<?>[]constrpartypes=newClass[]{String.class,String.class};

//Create constructor object. parameter types
Constructor<?>constr=dummyClass.getConstructor(constrpartypes);

// create instance
Objectdummyto=constr.newInstance(newObject[]{"Java Programmer","India"});

// Arguments to be passed into method
Object[]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 output Console 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 in Variables

AltStyle によって変換されたページ (->オリジナル) /