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米",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.InvocationTargetException;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/12 18:09
*/
public class ObjectFactory
{
public static void main(String[] args)
{
// if(args.length < 1){
// System.exit(1);
// }
String[] params = new String[2];
params[0] = "com.shrimpking.t6.Person";
params[1] = "zhang";
try
{
Class<?> clz = Class.forName(params[0]);
//获取无参的构造方法
Constructor noArgsCons = clz.getConstructor();
Object obj = noArgsCons.newInstance();
System.out.println(clz);
System.out.println(obj);
if(params.length > 1){
Class paramClz = params[1].getClass();
//得到一个参数的有参构造
Constructor oneArgCons = clz.getConstructor(paramClz);
obj = oneArgCons.newInstance(params[1]);
System.out.println(paramClz);
System.out.println(obj);
}
}catch (ClassNotFoundException
| NoSuchMethodException
| InstantiationException
| IllegalAccessException
| InvocationTargetException e){
System.out.println(e.toString());
}
}
}