zoukankan      html  css  js  c++  java
  • 泛型

    每次一阅读源码简单的还能看懂,一遇到泛型相关的我就开始犯迷糊了,所以把泛型重新捡起来再巩固一遍吧--

    泛型:

      在程序中,如果用到了带<>的类或者接口,就要明确传入的具体引用类型

      泛型是编译时的技术,用于编译时期,运行时候,就会去除泛型

      在我们不确定操作类型的时候我们可以定义泛型

      泛型定义在类上

    @Data//lombok自定生成get set
    public class Generic<T> {
    	
    
    	private T p;
    	
    }
    

      

      泛型定义在方法上:需要注意的是当方法静态的时候,我们不能使用类上的泛型,如果静态方法使用泛型,必须将泛型定义在方法上

    public <W> void go(W ob) {
            
            System.out.print(ob.toString());
        }

      
      public  static <T> void go(T ob) {
            
            System.out.print(ob.toString());
        }
    
    

    eg:pojo转xml

    public static <T> String poToXML(T pojo) {

    XStream xstream =new XStream();
    xstream.alias("xml", pojo.getClass());//目的是将顶部的头类标签变为xml
    return xstream.toXML(pojo);
    }

    public static void main(String[] args) {
    TextMessage text =new TextMessage();
    text.setContent("cys");
    text.setCreateTime(System.currentTimeMillis()/100);

    String name =poToXML( text);

    System.out.print(name);



    }

      

       泛型接口:

    public interface Generic<T> {
        
    
        T getname();
        
        
    }
    
    class yui implements  Generic<String>{
    
        @Override
        public String getname() {
            // TODO Auto-generated method stub
            return "fdf";
        }
        
        
    }

    泛型限定 ----我们可以固定泛型属于那种类型

    public  static <T extends Integer>    void syu( T a) {
            
            System.out.println("a");
            
        }
    //我们的的参数必须的Integer类型
    public static void main(String[] args) { syu(1); }
    原创打造,多多指教
  • 相关阅读:
    Redis系列二 Redis数据库介绍
    Redis系列一 Redis安装
    SpringData系列四 @Query注解及@Modifying注解
    SpringData系列三 Repository Bean 方法定义规范
    SpringData系列二 Repository接口
    SpringData系列一 Spring Data的环境搭建
    ThinkPHP3.1.3 Fast & Simple OOP PHP Framework 显示错误
    STL学习系列之一——标准模板库STL介绍
    STL之二:vector容器用法详解
    STL使用总结
  • 原文地址:https://www.cnblogs.com/iscys/p/9539565.html
Copyright © 2011-2022 走看看