一款熬、class類的使用
- 1个唧、java靜態(tài)的成員渠退、普通數(shù)據(jù)類型類不是對象
- 2、類是對象脐彩,類是java.lang.Class類的實(shí)例對象碎乃。這個(gè)類稱為該類的類類型(class type)
- 3、只有java虛擬機(jī)可以創(chuàng)建class的實(shí)例對象
- 4惠奸、編譯時(shí)加載類為靜態(tài)加載類梅誓,運(yùn)行時(shí)刻加載類是動(dòng)態(tài)加載類。
--new創(chuàng)建對象是靜態(tài)加載類佛南,在編譯時(shí)刻就需要加載所有的可能使用到的類梗掰。
--使用Class.forName("類全程");為動(dòng)態(tài)加載類,在運(yùn)行時(shí)刻加載 - 5嗅回、測試代碼如下
public class ClassDemo {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
//Foo的實(shí)例化對象如何表示
Foo foo1 = new Foo(); //foo1即Foo的實(shí)例化對象
//Foo這個(gè)類也是一個(gè)實(shí)例化對象,是Class類的實(shí)例對象及穗,即任何一個(gè)類都是Class的實(shí)例對象
//表示方式1 -- 即任何一個(gè)類都有一個(gè)隱含的靜態(tài)成員變量class
Class class1 = Foo.class;
//表示方式2,已知該類的對象绵载,通過getClass方法獲得
Class class2 = foo1.getClass();
//class1 拥坛、class2 表示了Foo類的類類型(class type),class1=class2,即一個(gè)類只可能是Class類的一個(gè)實(shí)例對象
System.out.println( class1 == class2);
//表達(dá)方式3
Class class3 = Class.forName("com.tiandy.producer.Foo");
//class3 = class2 = class1
//通過class1、class2尘分、class3創(chuàng)建Foo的實(shí)例
Foo foo2 = (Foo)class1.newInstance();//需要有無參數(shù)的構(gòu)造方法
}
}
class Foo{}
測試代碼2
public class MethodUtil {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//要獲取print(int,int )方法
Abc abc = new Abc();
Class cla = abc.getClass();
//獲取方法,getMethod:獲取的事public方法猜惋;getDeclaredMethod自己聲明的方法。以下兩種方法均可培愁。
// Method method = cla.getMethod("pring",new Class[]{int.class,int.class});
Method method1 = cla.getMethod("print",int.class,int.class);
Method method2 = cla.getMethod("print",String.class,String.class);
//方法的反射操作
Object o = method1.invoke(abc,10,20);
Object o1 = method2.invoke(abc,"10","20");
System.out.println();
}
}
class Abc {
public void print(int a,int b){
System.out.println(a+b);
}
public void print(String a,String b){
System.out.println(a+b);
}
}
二著摔、方法的反射
- 1、方法的名稱和方法的參數(shù)列表才能唯一決定某個(gè)方法
- 2定续、方法的反射操作:method.invoke(對象谍咆,參數(shù)列表)
public class MethodUtil {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//要獲取print(int,int )方法
Abc abc = new Abc();
Class cla = abc.getClass();
//獲取方法,getMethod:獲取的事public方法;getDeclaredMethod自己聲明的方法私股。以下兩種方法均可摹察。
// Method method = cla.getMethod("pring",new Class[]{int.class,int.class});
Method method1 = cla.getMethod("print",int.class,int.class);
Method method2 = cla.getMethod("print",String.class,String.class);
//方法的反射操作
Object o = method1.invoke(abc,10,20);
Object o1 = method2.invoke(abc,"10","20");
System.out.println();
}
}
class Abc {
public void print(int a,int b){
System.out.println(a+b);
}
public void print(String a,String b){
System.out.println(a+b);
}
}
三、泛型的本質(zhì)
- 1.泛型只在編譯時(shí)有用倡鲸,用于防止代碼輸入錯(cuò)誤供嚎。運(yùn)行時(shí)去掉。