|
В следующем примере показано, как обращаться к методам динамически с помощью отражения.
import java.lang.reflect.*;
import java.io.*;
public class testReflect {
public static void main(String s[]) {
testReflect t = new testReflect();
try {
t.doit();
}
catch (Exception e) {
e.printStackTrace();
}
}
public void doit() throws Exception {
String aClass;
String aMethod;
// we assume that called methods have no argument
Class params[] = {};
Object paramsObj[] = {};
while (true) {
/* examples
Class: class1 Method: class1Method2
Class: java.util.Date Method: toString
Class: java.util.Date Method: getTime
*/
aClass = Input.Line("\nClass : ");
aMethod = Input.Line("Method: ");
// get the Class
Class thisClass = Class.forName(aClass);
// get an instance
Object iClass = thisClass.newInstance();
// get the method
Method thisMethod = thisClass.getDeclaredMethod(aMethod, params);
// call the method
System.out.println(thisMethod.invoke(iClass, paramsObj).toString());
}
}
static class Input {
public static String Line(String s) throws IOException {
BufferedReader input =
new BufferedReader(new InputStreamReader(System.in));
System.out.print(s);
return input.readLine();
}
}
}
class class1 {
public String class1method1() {
return "*** Class 1, Method1 ***";
}
public String class1method2() {
return "### Class 1, Method2 ###";
}
}
|
Следующий пример вызывает метод класса с 2 аргументами:
import java.lang.reflect.*;
public class TestReflect {
static void invoke(String aClass, String aMethod, Class[] params, Object[] args) {
try {
Class c = Class.forName(aClass);
Method m = c.getDeclaredMethod(aMethod, params);
Object i = c.newInstance();
Object r = m.invoke(i, args);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
invoke("Class1", "say", new Class[] {String.class, String.class},
new Object[]
{new String("Hello"), new String("World")});
}
}
class Class1 {
public void say( String s1, String s2) {
System.out.println(s1 + " " + s2);
}
}
|
|
|
Рефлексия мощный подход к анализу классов во время исполнения. Если новые классы добавить в ваше приложение динамического отражения затем используется для получения структуры класса.
Отражения используются специальные виды Java-класса: класс. Объект класса типа может содержать всю информацию о классе и геттер методы получения этой информации.
Этот пример кода извлекает структуре класса String. Он будет отображать имя конструкторов, заявил поля и методы к консоли.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
// Creates an object of type Class which contains the information of
// the class String
Class cl = Class.forName("java.lang.String");
// getDeclaredFields() returns all the constructors of the class.
Constructor cnst[] = cl.getConstructors();
// getFields() returns all the declared fields of the class.
Field fld[] = cl.getDeclaredFields();
// getMethods() returns all the declared methods of the class.
Method mtd[] = cl.getMethods();
System.out.println("Name of the Constructors of the String class");
for (int i = 0; i < cnst.length; i++) {
System.out.println(cnst[i].getName());
}
System.out.println("Name of the Declared fields");
for (int i = 0; i < fld.length; i++) {
System.out.println(fld[i].getName());
}
System.out.println("Name of the Methods");
for (int i = 0; i < mtd.length; i++) {
System.out.println(mtd[i].getName());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
|
|
Отражения используется для вызова метода, когда имя метода поставляется во время выполнения. Этот совет будет показывать пример кода для этого.
import java.lang.reflect.Method;
public class RunMthdRef {
public int add(int a, int b) {
return a+b;
}
public int sub(int a, int b) {
return a-b;
}
public int mul(int a, int b) {
return a*b;
}
public int div(int a, int b) {
return a/b;
}
public static void main(String[] args) {
try {
Integer[] input={new Integer(2),new Integer(6)};
Class cl=Class.forName("RunMthdRef");
Class[] par=new Class[2];
par[0]=Integer.TYPE;
par[1]=Integer.TYPE;
Method mthd=cl.getMethod("add",par);
Integer output=(Integer)mthd.invoke(new RunMthdRef(),input);
System.out.println(output.intValue());
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
|