简体   繁体   English

反射类Java

[英]Reflection class java

I have this two classes and i want that the second one ( DocumentiDiIdentitaList ) creates a list based on all the values of the variables declared in the first class( DocumentiDiIdentita ) 我有这两个类,我希望第二个类( DocumentiDiIdentitaList )基于在第一个类( DocumentiDiIdentita )中声明的变量的所有值创建一个列表

Actually i got this code 其实我得到了这段代码

public class DocumentiDiIdentita {

    public static final String CARTA_IDENTITA = "CI";
    public static final String CARTA_IDENTITA_AFTER_25_06_2003 = "CI_NEW";
    public static final String PASSAPORTO_CONSOLATO = "PC";
    public static final String PASSAPORTO_QUESTURA = "PQ";
    public static final String PASSAPORTO_ESTERO = "PE";
    public static final String PATENTE_MORIZZAZIONE = "PZ";
    public static final String PATENTE_PREFETTURA = "PT";
    public static final String PORTOARMI = "PM";
    public static final String PASSAPORTO="PA";

}

public static class DocumentiDiIdentitaList {
    private static Field[] fields = DocumentiDiIdentita.class.getFields();
    public static List documentTypes = Arrays.asList(fields);

}

but actually the list documentTypes cointains the name of the variables, not their values, so actually is: 但是实际上列表documentTypes包含变量的名称,而不是它们的值,因此实际上是:

CARTA_IDENTITA
CARTA_IDENTITA_AFTER_25_06_2003
PASSAPORTO_CONSOLATO
etc.

but i want: 但我想要:

CI
CI_NEW
PC
etc.

how can i do this? 我怎样才能做到这一点? (i have to run on java 1.4) (我必须在Java 1.4上运行)

The Java Reflections API allows you to operate programmatically on the meta model, ie classes, methods, fields etc. Which are the structural information of your code. Java Reflections API允许您以编程方式对元模型(即类,方法,字段等)进行操作。它们是代码的结构信息。 Which mean, when you obtain access to a Field instance, it refers to the field declared by a class and not an instance of the field of an class instance (aka object). 这意味着,当您获得对Field实例的访问权时,它引用的是由类声明的字段,而不是类实例(也称为对象)的字段的实例。

In order to get the value of a field using reflection, you have to read the value for a given instance using field.get(instance) . 为了使用反射获取字段的值,必须使用field.get(instance)读取给定实例的值。 In case of static fields and methods, the instance is the class itself. 对于静态字段和方法,实例是类本身。 But you cannot pass the class itself because the .class is an object with own fields and methods, so field.get(DocumentiDiIdentita.class) will not work. 但是您不能传递类本身,因为.class是具有自己的字段和方法的对象,因此field.get(DocumentiDiIdentita.class)将无法工作。 Instead, for accessing static values, you pass null as parameter. 相反,要访问静态值,请传递null作为参数。

In Java 1.4 and above you could do 在Java 1.4及更高版本中,您可以执行

 Field[] fields = DocumentiDiIdentita.class.getFields();
 List documentTypes = new ArrayList();
 for(int i = 0; i < fields.length; i++){
     Field f = fields[i];
     documentTypes.add(f.get(null));
 }

Since Java 5 you could use generics and for-each loop: 从Java 5开始,您可以使用泛型和for-each循环:

 Field[] fields = DocumentiDiIdentita.class.getFields();
 List<String> documentTypes = new ArrayList<String>(); 
 for(Field f : fields){
     documentTypes.add(f.get(null));
 }

In Java8 you could use streams 在Java8中,您可以使用流

List docTypes = Stream.of(DocumentiDiIdentita.class.getFields()).map(this::uncheckedGet).collect(Collectors.toList());

private Object uncheckedGet(Field f) {
    try {
        return f.get(null);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

For the sake of readability I ommitted the Exception handling for both java 1.4 and 1.5 examples above. 为了便于阅读,我省略了上述Java 1.4和1.5示例的异常处理。 You may replace the field.get call with the uncheckedGet method of the java 8 example or the reuse the exception handling. 您可以用java 8示例的uncheckedGet方法替换field.get调用,或者重用异常处理。

It's a little bit tricky to get to the static field value. 获取静态字段值有些棘手。 You need to pass null to get method like this: 您需要传递null以获得这样的方法:

public class DocumentiDiIdentitaList {

    public static void main(String[] args) {

        Field[] fields = DocumentiDiIdentita.class.getDeclaredFields();

            Arrays.stream(fields).forEach(f -> {

                try {

                    System.out.println(f.get(null));

                }
                catch (IllegalAccessException e) {}

            });
    }
}

Hope i helped:) 希望我有所帮助:)

-- edit -编辑

Sorry for java8 version:( could you check if get method works with null value? 抱歉Java8版本:(您能否检查get方法是否可以使用null值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM