package Reflect;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;
public class ReflectTool{
//根据全类名获得实例化对象(全类名:包名.类名)
public Object getObject(String className) {
try {
Class clazz=Class.forName(className);
return clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
//根据实例化对象获得实例化对象
public Object getObject(Object object) {
try {
Class clazz=object.getClass();
return clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
//根据全类名获得Class对象(全类名:包名.类名)
public static Class getClass(String className) {
try {
return Class.forName(className);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
//根据实例化对象获得Class对象
public static Class getClass(Object object) {
try {
return object.getClass();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
//根据实例化对象、属性名设置某属性值
public static <T> void setValue(Object object,String fieldName,T value) {
Class clazz=getClass(object);
try {
Field field=clazz.getField(fieldName);
field.setAccessible(true); //使得私有变量可以修改
field.set(object, value);
} catch (Exception e) {
e.printStackTrace();
}
}
//根据实例化对象、属性名获取某属性
public static <T> T getValue(Object object,String fieldName) {
Class clazz=getClass(object);
T t = null;
try {
Field field=clazz.getField(fieldName);
t=(T) field.get(object);
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
//根据实例化对象、方法名、方法里传入参数class数组、方法里传入参数具体值数组 调用某方法
public static Object invoke(Object object,String methodName,Class<?>[] parameterTypes,Object[] parameterValue) {
Class clazz=getClass(object);
Object obj=null;
try {
Method method=clazz.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
obj=method.invoke(object, parameterValue);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return obj;
}
//类加载器流获取配置文件对象(Properties)方法:路径必须要使用/分隔
public Properties getProperties(String path) {
ClassLoader classLoader=this.getClass().getClassLoader();
InputStream inputStream=classLoader.getResourceAsStream(path);
Properties properties=new Properties();
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return properties;
}
//文件流获取配置文件对象(Properties)方法:路径必须要使用\\分隔
public static Properties readProperties(String path) {
Properties properties=new Properties();
try {
FileInputStream fileInputStream=new FileInputStream(path);
properties.load(fileInputStream);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return properties;
}
}