0

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

2 Answers 2

4

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.

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

1 Comment

Note that if you want to actually access the private field, you'll need to make it accessible using setAccessible(). More information here.
3

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.

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.