简体   繁体   English

Java反射和scala类

[英]Java reflection & scala class

Given the following scala class : 给定以下scala类:

class Student (_name:String, _id:Long) {

private var name:String = _name;
private var id:Long = _id;

// 2nd C'tor
def this(_name:String) = this(_name,0);

// 3rd C'tor
def this(_id:Long) = this("No Name",_id);

def printDetails() {

  println("The student's name is : " + name);
  println("The student's id is : " + id);

}

}

and the following Java class: 和以下Java类:

public class StudentReflectionDemo {

public static void main (String[] args) {

    try {
        Class cl = Class.forName("ClassesAndObjects.Student");
        Method[] methods = cl.getMethods();
        Field[] fields = cl.getFields();

        System.out.println("The methods of the Student class are : ");

        for (int i = 0 ; i < methods.length; i++) {
            System.out.println(methods[i]);
        }

        System.out.println("The fields of the Student class are : ");

        for (int i = 0 ; i < fields.length; i++) {
            System.out.println(fields[i]);
        }

    }
    catch(ClassNotFoundException e) {
        e.printStackTrace();
    }


}

}

It does correctly output the Student class methods but it doesn't print the Student's class fields.. 它可以正确输出Student类的方法,但不会输出Student的类字段。

What am I missing here? 我在这里想念什么?

thanks 谢谢

In Java, the getFields() method returns only public fields. 在Java中, getFields()方法仅返回public字段。 To get all fields, use getDeclaredFields() , which will return all fields that are declared directly on the class. 要获取所有字段,请使用getDeclaredFields() ,它将返回直接在类上声明的所有字段。

If you look at the Javadoc for getFields() you see the answer: 如果查看getFields()的Javadoc,则会看到答案:

Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object. 返回一个包含Field对象的数组,该对象反映此Class对象表示的类或接口的所有可访问公共字段

You need to use getDeclaredFields() instead: 您需要使用getDeclaredFields()代替:

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. 返回一个Field对象数组,该数组反映由该Class对象表示的类或接口声明的所有字段。 This includes public, protected, default (package) access, and private fields, but excludes inherited fields. 这包括公共,受保护,默认(程序包)访问和私有字段,但不包括继承的字段。

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

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