泛型与注解

1、什么是泛型


1.1泛型的概念


泛型是 Java SE5 出现的新特性,泛型的本质是类型参数化或参数化类型,在不创建新的类型的情况下,通过泛型指定的不同类型来控制形参具体限制的类型

1.2泛型的意义


一般的类和方法,只能使用具体的类型:要么是基本类型,要么是自定义的类。如果要编写可以应用于多种类型的代码,这种刻板的限制对代码的束缚就会很大。

Java 在引入泛型之前,表示可变对象,通常使用 Object 来实现,但是在进行类型强制转换时存在安全风险。有了泛型后:

编译期间确定类型,保证类型安全,放的是什么,取的也是什么,不用担心抛出 ClassCastException 异常。
提升可读性,从编码阶段就显式地知道泛型集合、泛型方法等处理的对象类型是什么。
泛型合并了同类型的处理代码提高代码的重用率,增加程序的通用灵活性

泛型的上线和下线

泛型的上线

public static void main(String[] args) {
    // List<? extends Fruit>
    // 参数  集合  Fruit 或者是Fruit 的子类
    List<Pear> fruits = new ArrayList<>();
    fruits.add(new Pear());
   // csxx(fruits);
    //
}

/**
 * 通配符的上限
 * @param fruits
 */

public static void scSg(List<? extends Fruit> fruits){

    for (Fruit fruit : fruits) {
       fruit.eat();
    }
}

泛型的下线

public static void csxx(List<? super Apple> fruits){
    for (Object fruit : fruits) {
        Fruit fruit1=(Fruit)fruit;
        fruit1.eat();
    }
}
public static void main(String[] args) {
        // List<? extends Fruit>
        // 参数  集合  Fruit 或者是Fruit 的子类
        List<Apple> fruits = new ArrayList<>();
        fruits.add(new Apple());
        csxx(fruits);
        //
//        scSg(fruits);
    }

泛型的实际应用(增删改查)

泛型添加的方法

public static int add(Object object) {
    // object 是一个对象
    // 对象的class属性
    Class<?> aClass = object.getClass();
    // insert into 表名(列的字段,) values(?,?,?);
    //        Class<? > aClass = new TabMenu().getClass();
    MyTable annotation = (MyTable) aClass.getAnnotation(MyTable.class);
    String tablename = annotation.name(); // 表的名字

    String idColumn = "";
    List<String> columns = new ArrayList<>();

    List<String> columnVals = new ArrayList<>();
    // 查询表中的所有的数据
    // 获取实体类中的所有的属性名
    Field[] fields = aClass.getDeclaredFields();// 获取所有的属性
    // System.out.println("fields = " + fields.length);
//     获取属性上面的注解   获取注解的目的是要得到注解中的列的名字
    if (fields.length > 0) {
        for (Field field : fields) {

            field.setAccessible(true);// 暴力反射
            //System.out.println("field = " + field.getName());
            // 获取属性上面的 所有的注解
            Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
            // 循环
            if (declaredAnnotations.length > 0) {
                for (Annotation declaredAnnotation : declaredAnnotations) {
                    // 列的名字
                    if (declaredAnnotation instanceof MyId) {
                        MyId id = (MyId) declaredAnnotation;
                        idColumn = id.name();
                        //
                        columns.add(idColumn);
                        // field。get(对象)  获取对象中  field的值    获取的是公共的属性   私有的属性无法获取
                        //  获取列的值
                        try {
                            Object o = field.get(object);// 获取对应的属性的值
                            columnVals.add("'"+o+"'");
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        }


                    }
                    if (declaredAnnotation instanceof MyColumn) {
                        MyColumn column = (MyColumn) declaredAnnotation;
                        String value = column.value();
                        // System.out.println("普通的列的名字 = " + value);
                        columns.add(value);
                        try {
                            Object o = field.get(object);// 获取对应的属性的值
                            columnVals.add("'"+o+"'");
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        }

                    }

                }
            }



        }

    }

    // insert into 表名(列名) values (?,?,?)

    String columnNames = columns.toString().replace("[", "(").replace("]", ")");

    String colVal = columnVals.toString().replace("[", "(").replace("]", ")");

    String sql="insert into "+tablename+" "+columnNames+" values "+colVal;
    System.out.println(sql);
    int i=0;

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }

    try {
        Connection connection = DriverManager.getConnection("jdbc:mysql:///security?useSSL=false", "root", "root");
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
       i = preparedStatement.executeUpdate();
        System.out.println(i>=0?"成功":"失败");

    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

    return i;
}

泛型的修改的方法

public static int upd(Object object) {
        // object 是一个对象
        // 对象的class属性
        Class<?> aClass = object.getClass();
        // insert into 表名(列的字段,) values(?,?,?);
        //        Class<? > aClass = new TabMenu().getClass();
        MyTable annotation = (MyTable) aClass.getAnnotation(MyTable.class);
        String tablename = annotation.name(); // 表的名字

        String idColumn = "";
        String idval="";

        List<String> updateVal= new ArrayList<>();
        // 查询表中的所有的数据
        // 获取实体类中的所有的属性名
        Field[] fields = aClass.getDeclaredFields();// 获取所有的属性
        // System.out.println("fields = " + fields.length);
//     获取属性上面的注解   获取注解的目的是要得到注解中的列的名字
        if (fields.length > 0) {
            for (Field field : fields) {

                field.setAccessible(true);// 暴力反射
                //System.out.println("field = " + field.getName());
                // 获取属性上面的 所有的注解
                Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
                // 循环
                if (declaredAnnotations.length > 0) {
                    for (Annotation declaredAnnotation : declaredAnnotations) {
                        // 列的名字
                        if (declaredAnnotation instanceof MyId) {
                            MyId id = (MyId) declaredAnnotation;
                            idColumn = id.name();
                            //
                           // columns.add(idColumn);
                            // field。get(对象)  获取对象中  field的值    获取的是公共的属性   私有的属性无法获取
                            //  获取列的值
                            try {
                                Object o = field.get(object);// 获取对应的属性的值
                                //columnVals.add("'"+o+"'");

                                idval =idColumn+"="+"'"+o+"'";

                            } catch (IllegalAccessException e) {
                                throw new RuntimeException(e);
                            }


                        }

                        // 普通的列
                        if (declaredAnnotation instanceof MyColumn) {
                            MyColumn column = (MyColumn) declaredAnnotation;
                            String value = column.value();
                            // System.out.println("普通的列的名字 = " + value);
                           // columns.add(value);
                            try {
                                Object o = field.get(object);// 获取对应的属性的值
                                //columnVals.add("'"+o+"'");
                                String str=value+"="+"'"+o+"'";
                                updateVal.add(str);
                            } catch (IllegalAccessException e) {
                                throw new RuntimeException(e);
                            }

                        }

                    }
                }



            }

        }

        String replace = updateVal.toString().replace("[", "").replace("]", "");
        String sql="update "+tablename+" set "+replace+" where "+idval;


        int i=0;

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql:///security?useSSL=false", "root", "root");
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            i = preparedStatement.executeUpdate();
            System.out.println(i>=0?"成功":"失败");

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return i;
    }

泛型的查询的方法

public static void query(Class aclass){
        List<Map> mapList= new ArrayList<>();

        List<String> columns= new ArrayList<>();

//        Class<? > aClass = new TabMenu().getClass();
        MyTable annotation = (MyTable) aclass.getAnnotation(MyTable.class);
        String tablename=annotation.name(); // 表的名字
        // 查询表中的所有的数据
        // 获取实体类中的所有的属性名
        Field[] fields = aclass.getDeclaredFields();// 获取所有的属性
        // System.out.println("fields = " + fields.length);
//     获取属性上面的注解   获取注解的目的是要得到注解中的列的名字
        if(fields.length>0){
            for (Field field : fields) {
                //System.out.println("field = " + field.getName());
                // 获取属性上面的 所有的注解
                Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
                // 循环
                if(declaredAnnotations.length>0){
                    for (Annotation declaredAnnotation : declaredAnnotations) {
                        // 列的名字
                        if (declaredAnnotation instanceof  MyId){
                            MyId id= (MyId) declaredAnnotation;
                            String name = id.name();
                            // System.out.println("主键的名字 = " + name);
                            columns.add(name);
                        }
                        if(declaredAnnotation instanceof  MyColumn){
                            MyColumn column = (MyColumn) declaredAnnotation;
                            String value = column.value();
                            // System.out.println("普通的列的名字 = " + value);
                            columns.add(value);
                        }

                    }
                }

            }

        }
        //  select id, mname, icon, pid, mcode, url
        String s = columns.toString();
        String replace = s.replace("[", "").replace("]", "");
        String sql = " select "+replace+" from "+tablename;
        System.out.println("sql = " + sql);

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql:///security?useSSL=false", "root", "root");
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();

            //获取jdbc的元数据
            ResultSetMetaData metaData = preparedStatement.getMetaData();
            int columnCount = metaData.getColumnCount();
            while(resultSet.next()){
                //
                Map map = new HashMap();
                for (int i = 0; i < columnCount; i++) {
                    Object object = resultSet.getObject(i+1);
                    String columnName = metaData.getColumnName(i + 1);
                    map.put(columnName,object);
                }
                mapList.add(map);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("mapList = " + mapList);
    }

泛型删除的方法

public  static void delete(Class aclass,Object idVal){
//        Class<? > aClass = new TabMenu().getClass();
        MyTable annotation = (MyTable) aclass.getAnnotation(MyTable.class);
        String tablename=annotation.name(); // 表的名字

        String idColumn="";
        // 查询表中的所有的数据
        // 获取实体类中的所有的属性名
        Field[] fields = aclass.getDeclaredFields();// 获取所有的属性
        // System.out.println("fields = " + fields.length);
//     获取属性上面的注解   获取注解的目的是要得到注解中的列的名字
        if(fields.length>0){
            for (Field field : fields) {
                //System.out.println("field = " + field.getName());
                // 获取属性上面的 所有的注解
                Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
                // 循环
                if(declaredAnnotations.length>0){
                    for (Annotation declaredAnnotation : declaredAnnotations) {
                        // 列的名字
                        if (declaredAnnotation instanceof  MyId){
                            MyId id= (MyId) declaredAnnotation;
                            idColumn= id.name();

                        }

                    }
                }

            }

        }
        //  select id, mname, icon, pid, mcode, url

        String sql = " delete from  "+tablename+ " where "+idColumn+"="+idVal;
        System.out.println("sql = " + sql);

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql:///security?useSSL=false", "root", "root");
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            int i = preparedStatement.executeUpdate();
            System.out.println(i>=0?"成功":"失败");

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

  • 24
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值