Code:
Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;/*** Reflection Features: * Can dynamically load a class during operation, dynamic new one object * Dynamic understanding of the structure inside the object, the dynamic invocation of some method of this object * Reflection benefits: * In the configuration file only write the name of the class, you can dynamically load the class in *@authorAdministrator **/ Public classtestreflection { Public Static voidMain (string[] args)throwsclassnotfoundexception, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception{//String str = "T";String str =Readproperties.getclassname (); //load the class into memory and return to type class. Class CLS =class.forname (str); Object o= Cls.newinstance ();//new An Object//get all the public methods of the CLS classMethod[] Methods =Cls.getmethods (); /*//Read all method names for (method M:methods) {System.out.println (M.getname ()); }*/ //Call method m2 for(Method m:methods) {if(M.getname (). Equals ("M2")){ //variable parameter method, O is the object of newM.invoke (o); } if(M.getname (). Equals ("M1")){ //methods of variable parametersM.invoke (o,1,9); //get the parameter type of the M1 method for(Class paramtype:m.getparametertypes ()) {System.out.println (Paramtype.getname ()); } } if(M.getname (). Equals ("GetS")){ //get the return value type of the Gets methodClass ReturnType =M.getreturntype (); System.out.println ("GetS ReturnType is:" +returntype); } } }}classT {Static{ //tests whether the class is load-to-memorySystem.out.println ("T loaded ..."); } PublicT () {//tests whether T is calledSystem.out.println ("T constructed ..."); } inti; String s; Public voidM1 (intIintj) { This. i = i+J; System.out.println ("I =" + This. i); } Public voidm2 () {System.out.println ("M2 invoked ..."); } PublicString GetS () {returns; }}View Code
Read the code for the properties configuration:
Configuration file Contents:
Class=t
ImportJava.io.InputStream;Importjava.util.Properties; Public classReadProperties {Static PrivateString ClassName =NULL; Static{loads ();}synchronized Static Public voidloads () {if(ClassName = =NULL) {InputStream is= ReadProperties.class. getResourceAsStream ("/test.properties"); Properties Dbprops=NewProperties (); Try{dbprops.load (IS); ClassName= Dbprops.getproperty ("Class"); } Catch(Exception e) {System.err.println ("Cannot read the properties file." + "Make sure that the configuration file is in the path specified in Classpath"); } } } Public StaticString GetClassName () {if(classname==NULL) loads (); returnClassName;} }View Code
Operation Result:
T loaded ...
T constructed ...
M2 invoked ...
I =10
Int
Int
GetS returntype Is:class java.lang.String
Java reflection Mechanism _ Read Properties