反射机制:Class,Field,Method,Construts,Array
import java.lang.reflect.Method;
public class DumpMethods
{
public static void main(String[] args) throws Exception
{
Class<?> classType = Class.forName(args[0]);//"java.lang.String"//得到一个class对象
Method[] methods = classType.getDeclaredMethods();//得到所有声明方法
for(Method method : methods)
{
System.out.println(method);
}
}
}
//反射类的对象,并调用方法
public class InvokeTester
{
public int add(int param1, int param2)
{
return param1 + param2;
}
public String echo(String message)
{
return "hello: " + message;
}
public static void main(String[] args) throws Exception
{
// InvokeTester test = new InvokeTester();
// System.out.println(test.add(1, 2));
// System.out.println(test.echo("tom"));
Class<?> classType = InvokeTester.class;//还有两种方式forName()、object.getClass():
Object invokeTester = classType.newInstance();
// System.out.println(invokeTester instanceof InvokeTester);
Method addMethod = classType.getMethod("add", new Class[] { int.class,
int.class });
Object result = addMethod.invoke(invokeTester, new Object[]{1, 2});
System.out.println((Integer)result);
System.out.println("---------------------");
Method echoMethod = classType.getMethod("echo", new Class[]{String.class});
Object result2 = echoMethod.invoke(invokeTester, new Object[]{"tom"});
System.out.println((String)result2);
}
}
//反射机制的使用
public class ReflectTester
{
// 该方法实现对Customer对象的拷贝操作
public Object copy(Object object) throws Exception
{
Class<?> classType = object.getClass();//这是第三种方式反射类
Object objectCopy = classType.getConstructor(new Class[] {})
.newInstance(new Object[] {});//其实里面的参数new Object[]{},如果是不带参数的构造方法,则可以用null来代替。
// 获得对象的所有成员变量
Field[] fields = classType.getDeclaredFields();
for (Field field : fields)
{
String name = field.getName();
String firstLetter = name.substring(0, 1).toUpperCase();// 将属性的首字母转换为大写
String getMethodName = "get" + firstLetter + name.substring(1);//这个字符串截取相当于name.substring(1,name.length);
String setMethodName = "set" + firstLetter + name.substring(1);
Method getMethod = classType.getMethod(getMethodName,
new Class[] {});
Method setMethod = classType.getMethod(setMethodName,
new Class[] { field.getType() });//这个field.getType()类似int.class
Object value = getMethod.invoke(object, new Object[] {});//object对象已经的参数已经被赋值 new Object[]{}是null
setMethod.invoke(objectCopy, new Object[] { value });objectCopy对象本来是null的,但被赋值后,就是object
}
// 以上两行代码等价于下面一行
// Object obj2 = classType.newInstance();
// System.out.println(obj);
return objectCopy;
Array动态反射数组介绍
public class ArrayTester1
{
public static void main(String[] args) throws Exception
{
Class<?> classType = Class.forName("java.lang.String");
Object array = Array.newInstance(classType, 10);//表示String字符串的长度是10
Array.set(array, 5, "hello");//设置index是5的值
String str = (String)Array.get(array, 5);得到对应的值
System.out.println(str);
}
}
Array的实例化多维数组
public class ArrayTester2
{
public static void main(String[] args)
{
int[] dims = new int[] { 5, 10, 15 };
Object array = Array.newInstance(Integer.TYPE, dims);
System.out.println(array instanceof int[][][]);
Object arrayObj = Array.get(array, 3);
arrayObj = Array.get(arrayObj, 5);
Array.setInt(arrayObj, 10, 37);
int[][][] arrayCast = (int[][][]) array;
System.out.println(arrayCast[3][5][10]);
// System.out.println(Integer.TYPE);//int,它返回的是原生数据类型,相当于int.class
// System.out.println(Integer.class);//class java.lang.Integer
}
}
输出结果:true
37
//得到反射类的层次结构
public class ClassTest
{
public static void main(String[] args)
{
Class<?> classType = Child.class;
System.out.println(classType);//Child
classType = classType.getSuperclass();
System.out.println(classType);//Parent
classType = classType.getSuperclass();
System.out.println(classType);//Object
classType = classType.getSuperclass();
System.out.println(classType);//null
}
}
class Parent
{
}
class Child extends Parent
{
}
//用反射机制获取类中private的方法
public class Private
{
private String sayHello(String name)
{
return "hello: " + name;
}
}
public class TestPrivate
{
public static void main(String[] args) throws Exception
{
Private p = new Private();
Class<?> classType = p.getClass();
Method method = classType.getDeclaredMethod("sayHello",
new Class[] { String.class });//这里必须用DeclaredMethod方法,因为它可以访问private,而getMethod仅仅能访问公共的修饰符,不能访问私有。
method.setAccessible(true);//压制Java的访问控制检查,设置为true表示可以访问private
String str = (String)method.invoke(p, new Object[]{"zhangsan"});
System.out.println(str);
}
}
//用反射机制访问私有属性
public class Private2
{
private String name = "zhangsan";
public String getName()
{
return name;
}
}
public class TestPrivate2
{
public static void main(String[] args) throws Exception
{
Private2 p = new Private2();
Class<?> classType = p.getClass();
Field field = classType.getDeclaredField("name");
field.setAccessible(true);//压制Java对访问修饰符的检查
field.set(p, "lisi");
System.out.println(p.getName());
}
}