Java 中,無論生成多個(gè)類的對象,這些對象都會對應(yīng)于同一個(gè)Class對象
2.獲取某個(gè)類或某個(gè)對象所對應(yīng)的Class對象常用的3種方式
a)使用Class類的靜態(tài)方法forName:Class.forName("java.lang.String")
b)使用類語法String.class
c)使用對象的getClass()方法:String s ="aa";
Class<?> clazz= s.getClass();
不帶參數(shù)的構(gòu)造方法,生成對象
a)先獲得Class對象,然后通過Class對象newInstance() 方法直接生成對象。
b) 先獲得Class對象,然后通過該對象獲得對應(yīng)的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);
}