-
September 26th, 2009, 05:06 PM
#1
How do i check if a Field type of a variable is an array type?
So yeah, im using reflection, and im getting every variable within my class. So I start with Field f being equal to some field i have, then depending on whether the variable is an array or normal type, i would like to print it. The reason why i want to check this is because if its just a normal type, i can say object.toString() and be all set, but if its an array, i need to use Arrays.toString(object); If i left out any viable info you may need, let me know.
This is the idea of what i want to do, but it wont compile, any ideas? an example of an "array" field would be something like public String[] = {"this", "array"}; public int[] = {1, 3, 5}; ...
StringBuilder b = new StringBuilder();
if(f.getType() instanceof Array){
b.append(Arrays.toString((Object[])f.get(target)));
}
else{
b.append(f.get( target ));
}
it says
1 error found:
Error: C:\CS stuff\Prog2\MyReflectionPrinter.java:86: inconvertible types
found : java.lang.Class<capture#975 of ?>
required: java.lang.reflect.Array
-
September 27th, 2009, 07:48 AM
#2
Re: How do i check if a Field type of a variable is an array type?
Use Field.toGenericString(), which will have a pair of brackets [] per each dimension of the array.
-
September 27th, 2009, 09:14 AM
#3
Re: How do i check if a Field type of a variable is an array type?
You can do it two ways:
Code:
Field f = getField(...);
if (f.getType().isArray()) {
... // it's an array
}
if (f.get(target) instanceof Object[]) { // where 'target' is the owner instance
... // it's an array
}
Although the 'instanceof' version is more verbose, it's much more efficient than the 'isArray()' call, and returns false for a null reference intstead of throwing an exception.
The person who says it cannot be done should not interrupt the person doing it...
Chinese proverb
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
-
September 27th, 2009, 12:39 PM
#4
Re: How do i check if a Field type of a variable is an array type?
oh my god thank you dlorde, u nailed it first try. thanks so much, i tried emailing my professor and he didnt help jack squat so you really helped out ^_^.
(i used the
if (f.get(target) instanceof Object[]) { // where 'target' is the owner instance
... // it's an array
}
implementation, thanks)
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|