You are on page 1of 11

Determining If an Object Is an Array

public class Main {


public static void main(String[] argv t!ro"s #$ception {
boolean b % &&'get(lass('isArray()
if (b {
System'out'println(&object is an array&)
*
*
*
+++++++
,-
- file. ArrayDemo'java
- pac/age. oreilly'!cj'reflection
-
- 0!is soft"are is granted under t!e terms of t!e (ommon 1ublic
2icense3
- (123 "!ic! may be found at t!e follo"ing 452.
- !ttp.,,"""+678'ibm'com,developer"or/s,oss,(12v6'9'!tm
-
- (opyrig!t(c 799:+799; by t!e aut!ors indicated in t!e <aut!or
tags'
- All 5ig!ts are 5eserved by t!e various aut!ors'
-
========== DO >O0 #DI0 A?O@# 0AIS 2I># ========== -,
import java'lang'reflect'Array)
,--
- Demonstrates t!e use of t!e Array class'
-
- <aut!or Ba !ref%mailto./rayt!e<arcor'deC5obert Simmons jr'
(/rayt!eB,aC
- <version D5evisionD
-,
public class ArrayDemo {
,--
- (opy an array and return t!e copy'
-
- <param input 0!e array to copy'
-
- <return 0!e coppied array'
-
- <t!ro"s IllegalArgument#$ception If input is not an array'
-,
public static Object copyArray(final Object input {
final (lass type % input'get(lass()
if (Etype'isArray( {
t!ro" ne" IllegalArgument#$ception()
*
final int lengt! % Array'get2engt!(input)
final (lass component0ype % type'get(omponent0ype()
final Object result % Array'ne"Instance(component0ype3
lengt!)
for (int id$ % 9) id$ B lengt!) id$FF {
Array'set(result3 id$3 Array'get(input3 id$)
*
return result)
*
,--
- 5un t!e demo'
-
- <param args (ommand line arguments (ignored'
-,
public static void main(final String[] args {
try {
int[] $ % ne" int[] { 73 :3 G3 H3 ; *)
c!ar[] y % ne" c!ar[] { IaI3 IJI3 IeI *)
String[] J % ne" String[] { &Kim&3 &Ko!n&3 &Koe& *)
System'out'println(& ++ $ and y ++&)
outputArrays($3 y)
System'out'println(& ++ $ and copy of $ ++&)
outputArrays($3 copyArray($)
System'out'println(& ++ y and copy of y ++&)
outputArrays(y3 copyArray(y)
System'out'println(& ++ J and copy of J ++&)
outputArrays(J3 copyArray(J)
* catc! (final #$ception e$ {
e$'printStac/0race()
*
*
,--
- 1rint out 7 arrays in columnar format'
-
- <param first 0!e array for t!e first column'
- <param second 0!e array for t!e second column'
-
- <t!ro"s IllegalArgument#$ception LL4>DO(4M#>0#DLL
-,
public static void outputArrays(final Object first3 final
Object second {
if (Efirst'get(lass(
'isArray( {
t!ro" ne" IllegalArgument#$ception(&first is not an
array'&)
*
if (Esecond'get(lass(
'isArray( {
t!ro" ne" IllegalArgument#$ception(&second is not an
array'&)
*
final int lengt!Mirst % Array'get2engt!(first)
final int lengt!Second % Array'get2engt!(second)
final int lengt! % Mat!'ma$(lengt!Mirst3 lengt!Second)
for (int id$ % 9) id$ B lengt!) id$FF {
System'out'print(&[& F id$ F &]Nt&)
if (id$ B lengt!Mirst {
System'out'print(Array'get(first3 id$ F &NtNt&)
* else {
System'out'print(&NtNt&)
*
if (id$ B lengt!Second {
System'out'print(Array'get(second3 id$ F &Nt&)
*
System'out'println()
*
*
*
,- ========== #nd of Mile ========== -,
+++++
Create array with Array.newInstance
import static java'lang'System'out)
import java'lang'reflect'Array)
import java'lang'reflect'(onstructor)
import java'lang'reflect'Invocation0arget#$ception)
import java'util'Arrays)
import java'util'rege$'Matc!er)
import java'util'rege$'1attern)
public class Array(reator {
private static String s % &java'mat!'?igInteger bi[] % { 67:3
7:83 :8; *&)
private static 1attern p % 1attern
'compile(&ONNs-(NNSFNNs-NN"FNN[NN]'-NN{NNs-([O*]
FNNs-NN*&)
public static void main(String''' args {
Matc!er m % p'matc!er(s)
if (m'find( {
String c>ame % m'group(6)
String[] c@als % m'group(7'split(&[NNs3]F&)
int n % c@als'lengt!)
try {
(lassBPC c % (lass'for>ame(c>ame)
Object o % Array'ne"Instance(c3 n)
for (int i % 9) i B n) iFF {
String v % c@als[i])
(onstructor ctor % c'get(onstructor(String'class)
Object val % ctor'ne"Instance(v)
Array'set(o3 i3 val)
*
Object[] oo % (Object[] o)
out'format(&Qs[] % QsQn&3 c>ame3 Arrays'toString(oo)
,, production code s!ould !andle t!ese e$ceptions more
gracefully
* catc! ((lass>otMound#$ception $ {
$'printStac/0race()
* catc! (>oSuc!Met!od#$ception $ {
$'printStac/0race()
* catc! (IllegalAccess#$ception $ {
$'printStac/0race()
* catc! (Instantiation#$ception $ {
$'printStac/0race()
* catc! (Invocation0arget#$ception $ {
$'printStac/0race()
*
*
*
*
+++++++++++++++++++++++++
Is field an array
import static java'lang'System'out)
import java'lang'reflect'Mield)
public class ArrayMind {
public static void main(String''' args {
boolean found % false)
try {
(lassBPC cls % (lass'for>ame(args[9])
Mield[] flds % cls'getDeclaredMields()
for (Mield f . flds {
(lassBPC c % f'get0ype()
if (c'isArray( {
found % true)
out'format(&QsQn& F & Mield. QsQn&
F & 0ype. QsQn& F & (omponent 0ype. Qs
Qn&3 f3 f
'get>ame(3 c3 c'get(omponent0ype()
*
*
if (Efound {
out'format(&>o array fieldsQn&)
*
,, production code s!ould !andle t!is e$ception more
gracefully
* catc! ((lass>otMound#$ception $ {
$'printStac/0race()
*
*
*
+++++++
(reate integer array "it! Array'ne"Instance
import static java'lang'System'out)
import java'lang'reflect'Array)
public class Array0rouble {
public static void main(String''' args {
Object o % Array'ne"Instance(int'class3 9)
int[] i % (int[] o)
int[] j % ne" int[9])
out'format(&i'lengt! % Qd3 j'lengt! % Qd3 args'lengt! % Qd
Qn&3 i'lengt!3
j'lengt!3 args'lengt!)
Array'getInt(o3 9) ,, ArrayInde$OutOf?ounds#$ception
*
*
++++++++++++++
4se Array'setInt to fill an array
import static java'lang'System'err)
import java'lang'reflect'Array)
public class Array0roubleAgain {
public static void main(String''' args {
Integer[] ary % ne" Integer[7])
try {
Array'setInt(ary3 93 6) ,, IllegalArgument#$ception
,, production code s!ould !andle t!ese e$ceptions more
gracefully
* catc! (IllegalArgument#$ception $ {
err'format(&4nable to bo$Qn&)
* catc! (ArrayInde$OutOf?ounds#$ception $ {
$'printStac/0race()
*
*
*
+++++++++++++++++++++++++++
4se Array'setS!ort and Array'set2ong
import java'lang'reflect'Array)
public class Array0rouble0oo {
public static void main(String''' args {
Object o % ne" int[7])
Array'setS!ort(o3 93 (s!ort 7) ,, "idening3 succeeds
Array'set2ong(o3 63 72) ,, narro"ing3 fails
*
*
++++++++++++++++++++++++++++++++++
Retting t!e 2engt! and Dimensions of an Array Object
import java'lang'reflect'Array)
public class Main {
public static void main(String[] argv t!ro"s #$ception {
Object o % ne" int[6][7][:])
int len % Array'get2engt!(o) ,, 6
System'out'println(len)
int dim % getDim(o) ,, :
System'out'println(dim)
*
public static int getDim(Object array {
int dim % 9)
(lass cls % array'get(lass()
"!ile (cls'isArray( {
dimFF)
cls % cls'get(omponent0ype()
*
return dim)
*
*
++++++++++++++++++++
Retting t!e (omponent 0ype of an Array Object
public class Main {
public static void main(String[] argv t!ro"s #$ception {
Object o % ne" int[6][7][:])
o'get(lass('get(omponent0ype()
*
*
+++
Array reflection and t"o dimensional array
import static java'lang'System'out)
import java'lang'reflect'Array)
public class (reateMatri$ {
public static void main(String''' args {
Object matri$ % Array'ne"Instance(int'class3 73 7)
Object ro"9 % Array'get(matri$3 9)
Object ro"6 % Array'get(matri$3 6)
Array'setInt(ro"93 93 6)
Array'setInt(ro"93 63 7)
Array'setInt(ro"63 93 :)
Array'setInt(ro"63 63 8)
for (int i % 9) i B 7) iFF
for (int j % 9) j B 7) jFF
out'format(&matri$[Qd][Qd] % QdQn&3 i3 j3 ((int[][]
matri$[i][j])
*
*
+++++++++++++++++++++++++++
class name for double and float array
class (lassInfoDemo7 {
public static void main(String[] args {
(lass c % String'class)
System'out'println(c'get>ame()
c % (lassInfoDemo7'class)
System'out'println(c'get>ame()
c % double'class)
System'out'println(c'get>ame()
c % float[]'class)
System'out'println(c'get>ame()
*
*
+++++
5eturns t!e lengt! of t!e specified array3 can deal "it! Object
arrays and "it! primitive arrays'
import java'lang'reflect'Array)
,--
- Operations on arrays3 primitive arrays (li/e
BcodeCint[]B,codeC and
- primitive "rapper arrays (li/e BcodeCInteger[]B,codeC'
-
- 0!is class tries to !andle BcodeCnullB,codeC input gracefully'
- An e$ception "ill not be t!ro"n for a BcodeCnullB,codeC
- array input' Ao"ever3 an Object array t!at contains a
BcodeCnullB,codeC
- element may t!ro" an e$ception' #ac! met!od documents its
be!aviour'
public class Main {
,,+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++
,--
- 5eturns t!e lengt! of t!e specified array'
- 0!is met!od can deal "it! BcodeCObjectB,codeC arrays and
"it! primitive arrays'
-
- If t!e input array is BcodeCnullB,codeC3 BcodeC9B,codeC is
returned'
-
- BpreC
- Array4tils'get2engt!(null % 9
- Array4tils'get2engt!([] % 9
- Array4tils'get2engt!([null] % 6
- Array4tils'get2engt!([true3 false] % 7
- Array4tils'get2engt!([63 73 :] % :
- Array4tils'get2engt!([&a&3 &b&3 &c&] % :
- B,preC
-
- <param array t!e array to retrieve t!e lengt! from3 may be
null
- <return 0!e lengt! of t!e array3 or BcodeC9B,codeC if t!e
array is BcodeCnullB,codeC
- <t!ro"s IllegalArgument#$ception if t!e object arguement is
not an array'
- <since 7'6
-,
public static int get2engt!(Object array {
if (array %% null {
return 9)
*
return Array'get2engt!(array)
*
*
+++++++++++++++++++++++++++++++++
Reneric class 5eflection
import java'lang'reflect'1arameteriJed0ype)
import java'lang'reflect'0ype)
import java'lang'reflect'0ype@ariable)
import java'util'Array2ist)
import java'util'2ist)
public class Reneric5eflect {
public static void main(String[] args {
0ype@ariable[] tv % 2ist'class'get0ype1arameters()
System'out'println(tv[9]'get>ame() ,, #
class String2ist e$tends Array2istBStringC {
*
0ype type % String2ist'class'getRenericSuperclass()
System'out'println(type)
1arameteriJed0ype pt % (1arameteriJed0ype type)
System'out'println(pt'getActual0ypeArguments([9])
*
*
+++++++++++++++++++++++
2oading a (lass 0!at Is >ot on t!e (lasspat!
A 452(lass2oader can be used to load classes in any directory'
import java'io'Mile)
import java'net'452)
import java'net'452(lass2oader)
public class Main {
public static void main(String[] argv t!ro"s #$ception {
Mile file % ne" Mile(&c.NN&)
452 url % file'to45I('to452()
452[] urls % ne" 452[] { url *)
(lass2oader cl % ne" 452(lass2oader(urls)
(lass cls % cl'load(lass(&com'mycompany'My(lass&)
*
*
++++++++++++++++++++++
Ret t!e pat! from "!ere a class is loaded
public class Main {
public static void main(String[] args {
Main csl % ne" Main()
csl'get(odeSource2ocation()
*
private void get(odeSource2ocation( {
System'out'println(&(ode source location. &
F
get(lass('get1rotectionDomain('get(odeSource('get2ocation()
*
*
+++++++++++++++++++++++++++++
Obtain from "!ere a (lass is loaded
public class Main {
public static void main(String args[] {
Main m % ne" Main()
System'out'println(m'get(lass('get>ame( F & is loaded from
&
F
m'get(lass('get1rotectionDomain('get(odeSource('get2ocation(
)
*
*
++++++++++++++++++++++++++++++++++
2oad t!e class source location from (lass'get5esource(
public class Main {
public static void main(String args[] {
(lass t!e(lass % Main'class)
java'net'452 u % t!e(lass'get5esource(&&)
System'out'println(&0!is class (MromS!ere is located at . &
F u)
*
*
+++++++++++++++++++
5eturns a reference to a file "it! t!e specified name t!at is
located some"!ere on t!e classpat!'
import java'io'Mile)
import java'util'String0o/eniJer)
,--
- A class containing useful utility met!ods relating to files'
-
- <aut!or David Rilbert
-,
public class Mile4tilities {
,--
- 5eturns a reference to a file "it! t!e specified name t!at
is located
- some"!ere on t!e classpat!' 0!e code for t!is met!od is an
adaptation of
- code supplied by Dave 1ostill'
-
- <param name
- t!e filename'
-
- <return a reference to a file or BcodeCnullB,codeC if no
file could be
- found'
-,
public static Mile findMileOn(lass1at!(final String name {
final String classpat! %
System'get1roperty(&java'class'pat!&)
final String pat!Separator %
System'get1roperty(&pat!'separator&)
final String0o/eniJer to/eniJer % ne"
String0o/eniJer(classpat!3 pat!Separator)
"!ile (to/eniJer'!asMore0o/ens( {
final String pat!#lement % to/eniJer'ne$t0o/en()
final Mile directoryOrKar % ne" Mile(pat!#lement)
final Mile absoluteDirectoryOrKar %
directoryOrKar'getAbsoluteMile()
if (absoluteDirectoryOrKar'isMile( {
final Mile target % ne"
Mile(absoluteDirectoryOrKar'get1arent(3 name)
if (target'e$ists( {
return target)
*
* else {
final Mile target % ne" Mile(directoryOrKar3 name)
if (target'e$ists( {
return target)
*
*
*
return null)
*
*
++++++++++++++++++++

You might also like