package com.shrimpking.t6;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/12 18:06
*/
public class Person
{
private String name;
public Person(){
this("匿名构造");
}
public Person(String name){
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public void run(int meters){
System.out.printf("%s跑了%d米%n",this.name,meters);
}
@Override
public String toString()
{
return "Person{" + "name='" + name + '\'' + '}';
}
private void helper(){
System.out.println("私有辅助方法");
}
}
package com.shrimpking.t6;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/12 18:48
*/
public class ObjectFactory3
{
public static void main(String[] args)
{
try
{
Class<?> clz = Class.forName("com.shrimpking.t6.Person");
//获取一个参数的构造方法
Constructor oneArgCons = clz.getConstructor(String.class);
Object obj = oneArgCons.newInstance("zhang");
System.out.println(obj);
//获取字段
Field f = clz.getDeclaredField("name");
// name字段是私有的
f.setAccessible(true);
f.set(obj,"wang");
System.out.println(obj);
f.setAccessible(false);
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
标签:String,System,name,Person,public,ObjectFactory3,out
From: https://blog.51cto.com/u_15356972/12016805