package test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
public class ReflectTest {
public static void main(String[] args)throws Exception
{
Reflect();
ReflectPoint rd1=new ReflectPoint(3,4);
changeChar(rd1);
String startClassName=args[0];
Method md=Class.forName(startClassName).getMethod("main", String[].class);
md.invoke(null, (Object)new String[]{"33","22","332"});
}
public static void changeChar(Object obj){
Field []fff=obj.getClass().getFields();
for(Field ff:fff)
{
if(ff.getType()==String.class)
{
String oldValue = null;
try {
oldValue = (String)ff.get(obj);
} catch (IllegalArgumentException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
String newValue=oldValue.replace('a','b');
try {
ff.set(obj, newValue);
} catch (IllegalArgumentException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
System.out.println(obj);
}
public static void Reflect()throws Exception
{
String st="abcde";
Class cla1=st.getClass();
Class cla2=String.class;
Class cla3=Class.forName("java.lang.String");
System.out.println(cla1==cla2);
System.out.println(cla1==cla3);
System.out.println(int.class.isPrimitive());
System.out.println(int.class==Integer.class);
System.out.println(int.class==Integer.TYPE);
System.out.println(int[].class.isArray());
Constructor cot=String.class.getConstructor(StringBuffer.class);
String st2=(String)cot.newInstance(new StringBuffer("ddd"));
System.out.println(st2.charAt(2));
ReflectPoint rd=new ReflectPoint(3,4);
Field fileX=rd.getClass().getField("x");
System.out.println(fileX.get(rd));
Field fileY=rd.getClass().getDeclaredField("y");
fileY.setAccessible(true);
System.out.println(fileY.get(rd));
Method md=String.class.getMethod("charAt", int.class);
System.out.println(md.invoke(st, 1));
int[] a1=new int[]{3,4,5};
int[][] a2={{2,3,4},{2}};
String[] a3={"d","s"};
Object ab1=a1;
Object ab2=a2;
Object ab3=a3;
Object[] ab5=a2;
Object[] ab6=a3;
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
System.out.println(Arrays.asList(a2));
System.out.println(Arrays.asList(a3));
}
}
class Dddd
{
public static void main(String[] args)
{
for(String arg:args)
{
System.out.print(arg);
}
}
}
class ReflectPoint
{
public int x;
private int y;
public String str1="abcdddd";
public String str2="base";
public String str3="bee";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
public String toString()
{
return str1+":"+str2+"::"+str3;
}
}
|
|