1. Code structure
.
├──com
│└──test
│└──mytest.java
└──maincall.java
2. Code Content
Mytest.java:
Package com.test; Public class mytest{ publicvoid do_test () { System.out.println ("Doing test ... \ n "); }}
Maicall.java
ImportJava.lang.reflect.Method; Public classmaincall{ Public Static voidMain (string[] args) {System.out.println ("Hello world!\n"); Class<?> MT =NULL; Try{MT= Class.forName ("Com.test.MyTest"); }Catch(Exception e) {e.printstacktrace (); } System.out.println ("ClassName:" +mt.getname ()); Try{Method Method= Mt.getmethod ("Do_test"); Method.invoke (Mt.newinstance ()); }Catch(Exception e) {e.printstacktrace (); } }}
3. Compiling
Javac Com/test/mytest.java
Javac Maincall.java
After successful compilation:
.
├──com
│└──test
│├──mytest.class
│└──mytest.java
├──maincall.class
└──maincall.java
4. Implementation
Java Maincall get output:
Hello world!
ClassName:com.test.MyTest
Doing test ...
Java Reflection Properties--Get other class instances and invoke their methods