0

I want to get private field of array of TextView via reflection, but I need to cast this field back to the array.

Field f= FieldUtils.getDeclaredField(ContentAdapter.ViewHolder.class, "button_massive", true);

Explicit cast like this TextView[] f1 = ((TextView[]) f) don't work.

Thank you in advance!

2
  • What's the error when you try that cast? Is using reflection really necessary? I would prefer that as last resort. Commented Nov 22, 2015 at 15:58
  • Inconvertible types, it won't compile, I'm using reflection for testing, that's why it's necessary Commented Nov 22, 2015 at 16:13

1 Answer 1

1

You're directly typecasting the Field type to array. That certainly won't work. What you want is to get the value of f, using Field#get() method. And then typecast that result to Object[].

Field f= FieldUtils.getDeclaredField(ContentAdapter.ViewHolder.class, "button_massive", true);
Object[] result = (Object[]) f.get(obj);

If you really want TextView type array, then you've to create the array using and populate it from above Object[]:

TextView[] f1 = new TextView[result.length];
// Iterate over the `Object` array, and populate `f1` array.

I haven't tested this out, but it should be working.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.