Java反射 - 获取数组对象的大小 [英] Java Reflection - Get size of array object

查看:262
本文介绍了Java反射 - 获取数组对象的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想,如果有知道怎么样了使用反射来得到一个数组对象的大小?

I was wondering if any knows hows to get the size of an array object using reflection?

我有一个包含类型的数组对象组件的轿车

I have a Vehicles component containing an array object of type Car.

Vehicles.java

public class Vehicles{

    private Car[] cars;

    // Getter and Setters
}

Car.java

public class Car{

    private String type;
    private String make;
    private String model;

    // Getter and Setters
}

我不知道我怎么会能够获得在汽车车辆内阵列使用Java反射机制的组成部分?

I was wondering how I would be able to get the size of the cars array within the vehicles component using Java Reflection?

我目前有以下几种:

final Field[] fields = vehicles.getClass().getDeclaredFields();

if(fields.length != 0){
    for(Field field : fields){
        if(field.getType().isArray()){
            System.out.println("Array of: " + field.getType());
            System.out.println(" Length: " + Array.getLength(field.getType()));
        }
    }
}

这将导致以下错误:

which results in the following error:

java.lang.IllegalArgumentException: Argument is not an array
    at java.lang.reflect.Array.getLength(Native Method)

任何想法?

推荐答案

该方法 Array.getLength(阵列)预计数组实例。在您code样品你在数组类型的字段调用它。它不会工作作为数组字段可以接受任何长度的数组!

The method Array.getLength(array) expects an array instance. In you code sample you are calling it on the array type for the field. It won't work as an array field can accept arrays of any lengths!

正确的code是:

Array.getLength(field.get(vehicles))

或更简单

Array.getLength(vehicles.cars);

或简单

vehicles.cars.length

以一个空照顾 vehicles.cars 价值虽然。

这篇关于Java反射 - 获取数组对象的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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