java 通配符的使用-upcast

本文深入探讨了Java中泛型的概念及其在数组类型转换中的应用,通过实例展示了编译器与运行时机制之间的差异,以及如何利用泛型避免常见的ArrayStoreException错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package localevidence;
//: generics/UnboundedWildcards1.java
//: generics/CovariantArrays.java
class Fruit {}
class Appleee extends Fruit {}
class Jonathan extends Appleee {}
class Orange extends Fruit {}
public class Testwildcats {
public static void main(String[] args) {
Fruit[] fruit = new Appleee[10];
fruit[0] = new Appleee(); // OK
fruit[1] = new Jonathan(); // OK
// Runtime type is Appleee[], not Fruit[] or Orange[]:
try {
// Compiler allows you to add Fruit:
fruit[0] = new Fruit(); // ArrayStoreException
} catch(Exception e) { System.out.println(e); }
try {
// Compiler allows you to add Oranges:
fruit[0] = new Orange(); // ArrayStoreException
} catch(Exception e) { System.out.println(e); }
}
} /* Output:
java.lang.ArrayStoreException: Fruit
java.lang.ArrayStoreException: Orange
*///:~
Fruit[] fruit = new Appleee[10];// 这是实例化fruit数组为appleee类型

  但是编译没有错误,但是在runtime的时候为啥报错呢?

This makes sense to the compiler, because it has a Fruit[] reference—why shouldn’t it allow a Fruit 

object, or anything descended from Fruit, such as Orange, to be placed into the array? So at compile time, this is allowed.

因为这对浏览器来说这是合理的,因为

Fruit[] fruit = new Appleee[10];
// Compiler allows you to add Fruit:
fruit[0] = new Fruit(); // ArrayStoreException

它有一个Fruit[]类型的申明,为啥不可以将Fruit 变量赋值给它呢,或者继承Fruit的子类呢?可以的编译器认为没有问题。

 The runtime array mechanism, however, knows that it’s dealing with an Apple [] and throws an exception when a foreign type is placed into the array.

但是runtime 运行机制却认为她是在处理Appleee[]类型的,所以如果你放入其它类型的就会报错。
"Upcast" is actually rather a misnomer here. What you’re really doing is assigning one array
to another.

"向上转型"事实上并不是不当,你实际在做的是将一种类型的数组赋值给另外一个数组。

 The array behavior is that it holds other objects, but because we are able to
upcast, it’s clear that the array objects can preserve the rules about the type of objects they
contain. It’s as if the arrays are conscious of what they are holding, so between the compile time checks and the runtime checks, you can’t abuse them.
This arrangement for arrays is not so terrible, because you do find out at run time that you’ve
inserted an improper type. But one of the primary goals of generics is to move such error
detection to compile time. So what happens when we try to use generic containers instead of
arrays?

The real issue is that we are talking about the type of the container, rather than the type that
the container is holding.
The type of flist is now List<? extends Fruit>, which you can read as "a list of any type
that’s inherited from Fruit." This doesn’t actually mean that the List will hold any type of
Fruit, however. The wildcard refers to a definite type, so it means "some specific type which
the flist reference doesn’t specify." So the List that’s assigned has to be holding some
specified type such as Fruit or Apple, but in order to upcast to flist, that type is a "don’t
actually care."

package localevidence;
public class Holder<T> {
	 private T value;
	 public Holder() {}
	 public Holder(T val) { value = val; }
	 public void set(T val) { value = val; }
	 public T get() { return value; }
	 public boolean equals(Object obj) {
	 return value.equals(obj);
	 }
	 public static void main(String[] args) {
	 Holder<Applee> Applee = new Holder<Applee>(new Applee());
	 Applee d = Applee.get();
	// Applee.set(d);
	 // Holder<Fruit> Fruit = Applee; // Cannot upcast
	 Holder<? extends Fruit> fruit = Applee; // OK
	 Fruit p = fruit.get();
	 d = (Applee)fruit.get(); // Returns ‘Object’
	 try {
	 Orange c = (Orange)fruit.get(); // No warning
	 } catch(Exception e) { System.out.println(e); }
	 // fruit.set(new Applee()); // Cannot call set()
	 // fruit.set(new Fruit()); // Cannot call set()
	 System.out.println(fruit.equals(d)); // OK
	 }
	} /* Output: (Sample)
	java.lang.ClassCastException: Applee cannot be cast to Orange
	true
	*///:
//: generics/SuperTypeWildcards.java
import java.util.*;
public class SuperTypeWildcards {
static void writeTo(List<? super Apple> apples) {
apples.add(new Apple());
apples.add(new Jonathan());
// apples.add(new Fruit()); // Error
}
} ///:~


转载于:https://my.oschina.net/u/2308739/blog/396594

资源下载链接为: https://pan.quark.cn/s/22ca96b7bd39 在当今的软件开发领域,自动化构建与发布是提升开发效率和项目质量的关键环节。Jenkins Pipeline作为一种强大的自动化工具,能够有效助力Java项目的快速构建、测试及部署。本文将详细介绍如何利用Jenkins Pipeline实现Java项目的自动化构建与发布。 Jenkins Pipeline简介 Jenkins Pipeline是运行在Jenkins上的一套工作流框架,它将原本分散在单个或多个节点上独立运行的任务串联起来,实现复杂流程的编排与可视化。它是Jenkins 2.X的核心特性之一,推动了Jenkins从持续集成(CI)向持续交付(CD)及DevOps的转变。 创建Pipeline项目 要使用Jenkins Pipeline自动化构建发布Java项目,首先需要创建Pipeline项目。具体步骤如下: 登录Jenkins,点击“新建项”,选择“Pipeline”。 输入项目名称和描述,点击“确定”。 在Pipeline脚本中定义项目字典、发版脚本和预发布脚本。 编写Pipeline脚本 Pipeline脚本是Jenkins Pipeline的核心,用于定义自动化构建和发布的流程。以下是一个简单的Pipeline脚本示例: 在上述脚本中,定义了四个阶段:Checkout、Build、Push package和Deploy/Rollback。每个阶段都可以根据实际需求进行配置和调整。 通过Jenkins Pipeline自动化构建发布Java项目,可以显著提升开发效率和项目质量。借助Pipeline,我们能够轻松实现自动化构建、测试和部署,从而提高项目的整体质量和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值