Dog对象
public class Dog {
private String name = "11";
public String name_ = "22";
public String name_2 ="==";
public String name_3 ="===";
public Dog(String name_) {
this.name_ = name_;
}
public Dog(){}
public void hi(){
System.out.println("hi===");
}
public void hi1(){}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", name_='" + name_ + '\'' +
'}';
}
}
常用方法
public class Main {
public static void main(String[] args) throws Exception{
Class<?> class_ = Class.forName("fanshe_lei.Dog");
// 获得包名
System.out.println(class_.getPackage().getName());
// 获得全名
System.out.println(class_.getName());
// 获得运行类型
System.out.println(class_.getClass());
// 获得Class 是加载哪个类的对象
System.out.println(class_);
// 对象实例化
Dog dog = (Dog) class_.getDeclaredConstructor().newInstance();
System.out.println(dog);
//==================================
// 获取属性
Field field = class_.getField("name_");
System.out.println(field.get(dog));
// 给属性改值
field.set(dog,"55");
System.out.println(field.get(dog));
// 获取全部的属性
Field[] fields = class_.getFields();
for (Field f:fields){
System.out.println(f);
System.out.println(f.get(dog));
}
//==================================
// 获取method
Method method = class_.getMethod("hi");
method.invoke(dog);
}
}
运行结果: