Class clazz = Class.forName("");
Class clazz = ref.getClass();
// 字段
Object instance = clazz.newInstance();
Field field = clazz.getDeclaredField("field"); // or getField() 获取public的字段
field.setAccessible(true); // private 变为 public
field.set(instance, "list");
// 获取方法
Method m = clazz.getDeclaredMethod("print", String.class); //方法的名字和方法的参数
// or clazz.getDeclaredMethod("print", null);
m.setAccessible(true); // private to public
m.invoke(instance, "parameters");
Constructor con = clazz.getConstructor(String.class, String.class);
con.newInstance("");
package io.zhpooer.test
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
import scala.beans.BeanProperty
classPerson {@BeanPropertyvar name: String = _
@BeanPropertyvar age: Int = _
overridedef toString = name + ", " + age
}
classReflectSpecextendsFlatSpecwithShouldMatchers {
it should "通过Java反射机制得到类的包名和类名" in {
val p = new Person;
println("包名字: " + p.getClass().getPackage().getName())
println("类名: " + p.getClass().getSimpleName())
println("完整类名: " + p.getClass().getName())
}
it should "通过Java反射机制,用 Class 创建类对" in {
val clazz = Class.forName("io.zhpooer.test.Person")
clazz.newInstance() match {
case p: Person =>
p.setAge(12)
p.setName("lest")
println(p)
}
}
it should "通过Java反射机制,用 Field 设置属性" in {
val clazz = Class.forName("io.zhpooer.test.Person")
val p = new Person;
p.setAge(12);
p.setName("test")
val field = clazz.getDeclaredField("name")
field.setAccessible(true)
field.set(p, "change")
println(field.get(p) + " " + p)
}
it should "通过Java反射机制得到类的一些成员信息 方法等" in {
val clazz = Class.forName("io.zhpooer.test.Person")
for ( field <- clazz.getDeclaredFields()) {
println(field.getModifiers() + " " + field.getName())
}
for ( method <- clazz.getDeclaredMethods()) {
println(method.getModifiers() + " " + method.getReturnType() + " " + method.getName())
}
}
}