package practice; import java.lang.reflect.Method; import java.util.*; /** * @author qingfeng * 功能:介绍泛型存在的必要性和泛型的使用 */ public class FanXing { public static void main(String[] args) { // TODO Auto-generated method stub /* ArrayList al = new ArrayList(); Dog dog = new Dog("huang", 12); al.add(dog); Dog dog1 = (Dog)al.get(0);//必须显性强制转换 Cat cat1 = (Cat)al.get(0);//如果写错类型,编译器不会报错 System.out.println("这是一只"+dog1.getName()); System.out.println("年龄"+dog1.getAge()); */ /* ArrayList<Dog> al = new ArrayList<Dog>();//泛型使用 al.add(new Dog("aa",23)); Dog dog1 = al.get(0);//隐式强制转换 System.out.println("这是一只"+dog1.getName()); */ Fan<String> fan1 = new Fan<String>("aaa"); fan1.showTypeName(); Fan<Cat> fan2 = new Fan<Cat>(new Cat()); fan2.showTypeName(); Fan<Integer> fan3 = new Fan<Integer>(123); fan3.showTypeName(); Fan<Float> fan4 = new Fan<Float>(123.1f); fan4.showTypeName(); System.out.println("---------------------"); //反射机制获取tyep类的很多信息 fan1.showInfo(); System.out.println("---------------------"); fan2.showInfo(); } } class Cat { public void showInfo1() { System.out.println("您好!"); } public void showInfo2() { System.out.println("您好!世界!"); } } class Dog { private String name; private int age; public Dog(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } class Fan<Type>//泛型类 { private Type temp; public Fan(Type temp) { this.temp = temp; } //得到temp的类型名称 public void showTypeName() { System.out.println("temp的传入的类型为:"+temp.getClass().getName()); } public void showInfo() { //反射机制 可以得到传入的type的很多信息! Method m[] = temp.getClass().getDeclaredMethods(); for(int i=0; i<m.length; i++) { System.out.println("Type类型所调用的方法:"+m[i].getName()); } } }