一个Java变量可以接受的原始类型或者对象的数组? [英] Can a single Java variable accept an array of either primitives or objects?

查看:210
本文介绍了一个Java变量可以接受的原始类型或者对象的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,对于读取数组中的元素一个方法,如何能程序员允许任何对象的数组或基元的数组被作为参数传递? 对象[] arrayName中将只接受对象的数组,和通用变量不接受原语。有没有一种方法能够接受类型的数组没有超载的方法是什么?

For example, for a single method that reads the elements of an array, how can the programmer allow either an array of objects or an array of primitives to be passed as the parameter? Object[] arrayName will only accept an array of Objects, and generic variables do not accept primitives. Is there a way to accept either type of array without overloading the method?

推荐答案

您可以通过任一类型的数组作为对象

You can pass an array of either type as an Object.

从那里,你必须使用反射。特别 IsArray的() ,的 getComponentType() 和的 isPrimitive() 会告诉方法是什么已经过去了。它的一些不幸邋邋遢遢的由基本数据类型介绍。

From there, you have to use reflection. In particular isArray(), getComponentType(), and isPrimitive() will tell the method what it has been passed. It's some of the unfortunate untidiness introduced by primitive data types.

这篇关于一个Java变量可以接受的原始类型或者对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆