• Java泛型反射机制(一)


    /**
     * 
     * @author Administrator
     * 功能:泛型的必要性(参数化类型)(安全简单)
     */
    package com.test;
    import java.util.*;
    
    public class Test {
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            
    //        ArrayList al = new ArrayList();
    //        //创建一只狗
    //        Dog dog1 = new Dog();
    //        //放入到集合中
    //        al.add(dog1);
            //该句会报错,ArrayList返回的是Object类型的必须强转或者使用泛型
            //Dog temp2 = al.get(0);
    //        //取出
    //        //强制类型转换时要求开发者对实际参数类型可以预知的情况下进行的,编译器不提示错误
            //存在安全隐患
    //        //Dog temp = (Dog)al.get(0);
    //        
    //        //编译器不报错,存在安全隐患,报类型转换异常
    //        //Cat temp = (Cat)al.get(0);
            
            //泛型的好处是在编译时检查类型的安全
            //使用泛型不会报错
            ArrayList<Dog> al = new ArrayList<Dog>();
            Dog temp = al.get(0);
        }
    }
    
    class Cat
    {
        private String color;
        private int age;
        public String getColor() {
            return color;
        }
        public void setColor(String color) {
            this.color = color;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        
        
    }
    
    class Dog
    {
        private String name;
        private int 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;
        }
        
        
    }
  • 相关阅读:
    java数据库访问类和接口
    数据删除的用法
    短信发送(M800)
    Spring注解开发(六)扩展原理
    观察者模式(Obeserver Pattern)
    Spring注解开发(五)声明式事务
    Spring注解开发(四)AOP原理与源码分析
    Spring注解开发(三)属性赋值与自动装配
    Spring注解开发(二)生命周期
    Spring注解开发(一)组件注册
  • 原文地址:https://www.cnblogs.com/beautiful-code/p/5347645.html
Copyright © 2020-2023  润新知