代码演示反射核心内容
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
- 通过反射技术调用方法
-
method.invoke(实例, method方法的实参列表)
-
如果是静态方法,在实例位置传递null
- @author Administrator
*/
public class Test06 {
public static void main(String[] args) throws Exception {
//1) 创建Class对象
Class<?> class1 = String.class;
//2) 创建实例, 通过Class对象创建实例,会调用无参构造
Object str1 = class1.newInstance(); //new String()
//反射构造方法,创建实例 String(byte[] bytes)
Constructor<?> constructor = class1.getConstructor( byte[].class );
byte[] bytes = {65,66,67,68,69,70};
Object str2 = constructor.newInstance(bytes); //new String( bytes )
//3)反射方法 equals(Object obj)
Method equalsM = class1.getMethod(“equals”, Object.class);
//4)调用方法,invoke( 实例, equals方法的实参 )
Object result = equalsM.invoke(str2, str1); //str2.equals(str1)
System.out.println( result );
result = equalsM.invoke(str2, “ABCDEF”); //str2.equals(“ABCDEF”);
System.out.println( result );
//5)反射 length()
Method lengthM = class1.getMethod(“length”, null);
result = lengthM.invoke(str1); //str1.length()
System.out.println( result );
result = lengthM.invoke(str2); //str2.length()
System.out.println( result );
//6)反射substring( int from, int to)
Method substringM = class1.getMethod(“substring”, int.class , int.class);
result = substringM.invoke(str2, 0 , 4); // str2.substring(0,4)
System.out.println( result );
//7) 反射静态方法, valueOf(int)
Method valueOfM = class1.getMethod("valueOf", int.class);
//在调用静态方法时, invoke(实例, 方法的实参), 在实例位置传递null
result = valueOfM.invoke(null, 456);
System.out.println( result );
//8)静态字段serialVersionUID
Field field = class1.getDeclaredField("serialVersionUID");
field.setAccessible(true);
System.out.println( field.get(null) );
}
}
上一篇: [转载]马化腾讲产品:让产品自己召唤人