Java 中,無論生成多個類的對象,這些對象都會對應于同一個Class對象
2.獲取某個類或某個對象所對應的Class對象常用的3種方式
a)使用Class類的靜態方法forName:Class.forName("java.lang.String")
b)使用類語法String.class
c)使用對象的getClass()方法:String s ="aa";
Class<?> clazz= s.getClass();
不帶參數的構造方法,生成對象
a)先獲得Class對象,然后通過Class對象newInstance() 方法直接生成對象。
b) 先獲得Class對象,然后通過該對象獲得對應的Construtor 對象,
package com.doodoosun;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectTest {
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 InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
Class<?> classType = ReflectTest.class;
Object reflectTest = classType.newInstance();
Method addMethod = classType.getMethod("add",new Class[]{int.class,int.class});
Object result = addMethod.invoke(reflectTest,new Object[]{1,2});
System.out.println("-------"+(Integer)result);
Method echoMethod = classType.getMethod("echo", new Class[]{String.class});
Object result2 = echoMethod.invoke(reflectTest, new Object[]{"tom"});
System.out.println(result2);
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectTest {
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 InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
Class<?> classType = ReflectTest.class;
Object reflectTest = classType.newInstance();
Method addMethod = classType.getMethod("add",new Class[]{int.class,int.class});
Object result = addMethod.invoke(reflectTest,new Object[]{1,2});
System.out.println("-------"+(Integer)result);
Method echoMethod = classType.getMethod("echo", new Class[]{String.class});
Object result2 = echoMethod.invoke(reflectTest, new Object[]{"tom"});
System.out.println(result2);
}