Service1.java
Package publicclass Service1 { publicvoid DoService1 () { System.out.println ("Business Method 1");} }
Service2.java
Package publicclass Service2 { publicvoid DoService2 () { System.out.println ("Business Method 1");} }
Spring.txt (D:\spring)
Class=reflection. Service1method=doservice1
Test.java
Packagereflection;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.lang.reflect.Constructor;ImportJava.lang.reflect.Method;Importjava.util.Properties; Public classTest {@SuppressWarnings ({"Rawtypes", "unchecked" }) Public Static voidMain (string[] args)throwsException {//get the class name and method name from Spring.txtFile Springconfigfile =NewFile ("D:\\spring.txt"); Properties Springconfig=NewProperties (); Springconfig.load (NewFileInputStream (springconfigfile)); String ClassName= (String) springconfig.get ("Class"); String MethodName= (String) springconfig.get ("Method"); //to create a class object from a class nameClass Clazz =Class.forName (className); //based on the name of the facet, get methodMethod m =Clazz.getmethod (methodName); //Get ConstructorConstructor C =Clazz.getconstructor (); //instantiate an object according to the constructorObject Service =c.newinstance (); //invoking the specified method of an objectM.invoke (service); }}
Lesson six Java reflection Get object properties and methods (via config file)