鑑於以下斯卡拉類:Java反射和斯卡拉類
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);
}
}
和下面的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();
}
}
}
它不正確輸出的學生類的方法,但它不打印學生類字段..
我在這裏錯過了什麼?
感謝
呃...嘿嘿。謝謝:) – Rouki
請注意,如果你想實際*訪問私人領域,你需要使用'setAccessible()'來訪問它。更多信息[這裏](http://www.onjava.com/pub/a/onjava/2003/11/12/reflection.html)。 –