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.Method;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/12 18:33
*/
public class ObjectFactory2
{
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");
//获取 run方法的对象
Method method = clz.getMethod("run", int.class);
//调用run
method.invoke(obj,1000);
//获取helper 方法的对象
method = clz.getDeclaredMethod("helper");
//helper方法是私有方法,正常时不可调用
// 通过设置可见性 ,来访问
method.setAccessible(true);
method.invoke(obj);
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
标签:反射,String,helper,method,Person,ObjectFactory2,public,name
From: https://blog.51cto.com/u_15356972/12016807