029--泛型的使用

1.简单的泛型使用

public class TUtils {

    public static void main(String[] args) {
//        Box name = new Box("corn");
//        System.out.println("name:" + name.getData());
        
        Box name = new Box("corn");
        Box age = new Box(712);
        System.out.println("name class:" + name.getClass());      // com.qqyumidi.Box
        System.out.println(name.getData().getClass());
        System.out.println();
        
        System.out.println("age class:" + age.getClass());        // com.qqyumidi.Box
        System.out.println(age.getData().getClass());
        System.out.println();
        
        System.out.println(name.getClass() == age.getClass());    // true   
    }
}

class Box {

    private T data;

    public Box() {
    }
    public Box(T data) {
        this.data = data;
    }

    public T getData() {
        return data;
    }

}

2.泛型工具类创建

public class TUtils2 {
    //1.构建
    private T t;  //不支持静态
    
    public T getT() {
        return t;
    }
    public String getClassType()  
    {  
        return t.getClass().getName();  
    }
    public TUtils2(T t) {
        super();
        this.t = t;
    }
    public TUtils2() {
        super();
    }
    
    //2.构建方法
    public void turnToClassObject(String string){
        System.out.println(t.getClass());
        if (t.getClass().isInstance(User.class)) {
            System.out.println("进行你要的操作:User:"+string);
        }else if (t.getClass().isInstance(Teacher.class)) {
            System.out.println("进行你要的操作:Teacher:"+string);
        }else if (t.getClass().isInstance(String.class)) {
            System.out.println("进行你要的操作:String:"+string);
        }else if (t.getClass().isInstance(ArrayList.class)) {
            System.out.println("进行你要的操作:ArrayList:"+string);
        }
    }
    
    //3.测试
    public static void main(String[] args) {
        new TUtils2<>(new Teacher()).turnToClassObject("DowneyJr");
        new TUtils2<>(new User()).turnToClassObject("DowneyJr");
        new TUtils2<>("beijing").turnToClassObject("DowneyJr");
        new TUtils2<>(new ArrayList()).turnToClassObject("DowneyJr");
    }

3.Demo下载地址:http://pan.baidu.com/s/1pKTMgPH

你可能感兴趣的:(029--泛型的使用)