专栏首页Jerry的SAP技术分享自己实现的Java装箱类,可以包裹任意类型

自己实现的Java装箱类,可以包裹任意类型

package generic;
// https://docs.oracle.com/javase/tutorial/java/generics/types.html
/*
 * A Simple Box Class

Begin by examining a non-generic Box class that operates on objects of any type. 
It needs only to provide two methods: set, which adds an object to the box, and get, which retrieves it:

public class Box {
    private Object object;

    public void set(Object object) { this.object = object; }
    public Object get() { return object; }
}
Since its methods accept or return an Object, you are free to pass in whatever you want, 
provided that it is not one of the primitive types. There is no way to verify, 
at compile time, how the class is used. One part of the code may place an Integer in the box and 
expect to get Integers out of it, while another part of the code may mistakenly pass in a String,
 resulting in a runtime error.
 */
public class Box<T> {
	// T stands for "Type"
    private T t;

    public void set(T t) { 
    	this.t = t; 
    	System.out.println("Set called: " + t);
    }
    public T get() { 
    	System.out.println("Get called: " + t);
    	return t; 
    }
    /*
     * Box<Integer> integerBox;
     * Like any other variable declaration, this code does not actually create a new Box object. It simply declares that integerBox will 
     * hold a reference to a "Box of Integer", which is
     *  how Box<Integer> is read.
     */
    static public void main(String[] arg){
    	Box<Integer> integerBox = new Box<Integer>();
    	integerBox.set(1);
    	System.out.println("value: " + integerBox.get());
    	
    	Box<String> stringBox = new Box<String>();
    	stringBox.set("Jerry");

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • How to update BOL entity property value via ABAP code

    Suppose I have one product with ID I042416 which could be found in CRM WebClient...

    Jerry Wang
  • Spring中的Spring JSR-250 注释

    Spring还使用基于 JSR-250 注释,它包括 @PostConstruct, @PreDestroy 和 @Resource 注释。

    Jerry Wang
  • How to update BOL entity property value via ABAP code

    Suppose I have one product with ID I042416 which could be found in CRM WebClient...

    Jerry Wang
  • 手撕SharePoint,脚踩Dropbox, Box的发家之路

    大学生辍学,然后在自家车库中打造出一个的创业神话是硅谷最老套的故事之一。不过,这样的故事几乎每隔几年就会发生一起,并由此就会出现一位改变世界的年轻企业家。

    人称T客
  • 原 数据字典+匿名委托模拟switch/c

    魂祭心
  • Python 不用selenium 带你高效爬取京东商品评论

    一天,一朋友扔给我一个链接https://item.jd.com/100000499657.html,让我看看这个歌商品的所有评论怎么抓取,我打开一看,好家伙,...

    cutercorley
  • C#构造函数里的base和this的区别

    父类的构造函数总是在子类之前执行的。既先初始化静态构造函数,后初始化子类构造函数。

    跟着阿笨一起玩NET
  • ASP.NET CORE Linux发布工具(文件对比 只上传差异文件;自动启停WebServer命令;上传完成自动预热WebServer)

    liulun
  • 【处理手记】Configuration system failed to initialize异常的另类原因

    度娘一番,发现市面上常见的原因是配置文件中的特定节点的位置不对,或者配置文件损坏等等,而这个程序根本没有使用内置的配置文件方案,而是用的ini,所以不适用我的问...

    AhDung
  • “爸爸,什么是机器学习呀?”

    原作:Daniel Tunkelang 安妮 编译自 Quora 量子位 出品 | 公众号 QbitAI 爸爸,什么是机器学习呀? 难以回答!抓了抓开始脱发的脑...

    量子位

扫码关注云+社区

领取腾讯云代金券