gpt4 book ai didi

Java 反射和 scala 类

转载 作者:行者123 更新时间:2023-12-01 07:31:43 24 4
gpt4 key购买 nike

给定以下 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);

}

}

以及以下 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();
}


}

}

它确实正确输出了 Student 类方法,但没有打印 Student 类字段..

我在这里缺少什么?

谢谢

最佳答案

在 Java 中,getFields() 方法仅返回 public 字段。要获取所有字段,请使用 getDeclaredFields() ,它将返回直接在类上声明的所有字段。

关于Java 反射和 scala 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16843231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com