反编译一个类
首先写一个配置文件test.properties
class = java.lang.String
然后进行反编译
/**
* 反编译一个类
* 从配置文件中读取到全类名 然后反编译这个类
*/
public class Reflect05 {
public static void main(String[] args) {
try {
//创建流对象
FileReader test = new FileReader("");
//创建集合对象
Properties properties = new Properties();
properties.load(test);
System.out.println(properties.getProperty("class"));
//开始反编译
StringBuilder str = new StringBuilder();
//获得字节码对象
Class aClass = Class.forName(properties.getProperty("class"));
str.append("class "+aClass.getSimpleName());
str.append("{\n");
//获得属性
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
str.append("\t");
str.append(Modifier.toString(declaredField.getModifiers())+" ");
str.append(declaredField.getType()+" ");
str.append(declaredField.getName()+"\n");
}
//反编译构造
Constructor[] declaredConstructors = aClass.getDeclaredConstructors();
//遍历
for (Constructor declaredConstructor : declaredConstructors) {
str.append("\n");
str.append("\t");
str.append(Modifier.toString(declaredConstructor.getModifiers())+" ");
str.append(declaredConstructor.getName()+" (");
//获取参数列表
Class[] parameterTypes = declaredConstructor.getParameterTypes();
//遍历参数列表
for (Class parameterType : parameterTypes) {
str.append(parameterType.getSimpleName()+",");
//deleteCharAt()删除指定下标的字符
str.deleteCharAt(str.length()-1);
}
str.append("){\n");
str.append("\n\t}\n");
//反编译方法
Method[] declaredMethods = aClass.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
str.append("\n");
str.append("\t");
str.append(Modifier.toString(declaredMethod.getModifiers())+" ");
str.append(declaredMethod.getReturnType()+" ");
str.append(declaredMethod.getName()+"(");
//获取参数列表
Class[] parameterTypes1 = declaredMethod.getParameterTypes();
for (Class parameterType : parameterTypes1) {
str.append(parameterType.getSimpleName()+",");
//切割最后一个逗号
str.deleteCharAt(str.length()-1);
}
str.append("){\n");
str.append("\n\t}");
}
}
str.append("}");
System.out.println(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}