package com.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author jack
* 2015-2-12
*
*/
class Test{
public String str;
public int num;
public Test(String str,int num){
this.str=str;
this.num=num;
}
public boolean showTest(){
System.out.println(str+num);
return true;
}
}
public class ReflectTest {
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {
Class<Test> testClass=Test.class;
Class[] testParamType=new Class[]{String.class,int.class};
Constructor<Test> testCtrl=testClass.getConstructor(testParamType);
Test test=(Test) testCtrl.newInstance("this is a num:",12);
test.showTest();
Field f =testClass.getField("str");
f.set(test, "I'm a num ");
Field f2=testClass.getField("num");
f2.set(test, 1234);
test.showTest();
Method m=testClass.getMethod("showTest", new Class[]{});
m.invoke(test, new Object[]{});
Test test2=new Test("d",1);
System.out.println(test2 instanceof Test);
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author jack
* 2015-2-12
*
*/
class Test{
public String str;
public int num;
public Test(String str,int num){
this.str=str;
this.num=num;
}
public boolean showTest(){
System.out.println(str+num);
return true;
}
}
public class ReflectTest {
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {
Class<Test> testClass=Test.class;
Class[] testParamType=new Class[]{String.class,int.class};
Constructor<Test> testCtrl=testClass.getConstructor(testParamType);
Test test=(Test) testCtrl.newInstance("this is a num:",12);
test.showTest();
Field f =testClass.getField("str");
f.set(test, "I'm a num ");
Field f2=testClass.getField("num");
f2.set(test, 1234);
test.showTest();
Method m=testClass.getMethod("showTest", new Class[]{});
m.invoke(test, new Object[]{});
Test test2=new Test("d",1);
System.out.println(test2 instanceof Test);
}
}