Java simple reflection exercise

Last night saw the reflection Java, which comes under the reflection do exercises,

Case : write a "framework" that can create objects of arbitrary classes, and perform any of these methods;

Premise: can not change any code in the class, you can create objects of any class, any method can be performed

Implementation: 1, +2 profile, reflecting

step:

(1) Create a simple Person class

public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void out(){
System.out.println("姓名:"+name+" 年龄:"+age);
}
}

(2) create a profile pro.properties

ClassName = testfs.Person
Method = out

(3) create the framework classes FsKj

{class FsKj public
@Test
public void testFsKj () {
// read the properties file
the Properties properties = new new the Properties ();
String ClassName = null;
String Method, = null;
the try {
// Get file field
properties.load (new FileInputStream ( "the src / pro.properties"));
ClassName = Properties.getProperty ( "ClassName");
Method, Properties.getProperty = ( "Method,");
System.out.println ( "acquired file field:" + "categories: "+ ClassName +" method: "method, +);
// Create bytecode object
Class = classp the Class.forName (ClassName);
// constructor obtaining
the constructor constructor = classp.getConstructor (String.class, int.class);
/ / create Object
Object person = constructor.newInstance ( "Joe Smith", 20);
// Get method
Method method = classp.getMethod(Method);
//运行方法
method.invoke(person);
System.out.println("SUCCESS");

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

(4) the method to add annotations on @Test class

(5) Run the process

result:

Get to file field: Class: testfs.Person method: out
Name: Joe Smith Age: 20
SUCCESS

Guess you like

Origin www.cnblogs.com/2019z/p/11422508.html