简体   繁体   中英

Java reflection & scala class

Given the following scala class :

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:

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..

What am I missing here?

thanks

In Java, the getFields() method returns only public fields. To get all fields, use getDeclaredFields() , which will return all fields that are declared directly on the class.

If you look at the Javadoc for getFields() you see the answer:

Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.

You need to use getDeclaredFields() instead:

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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