0%

Java利用反射机制反编译一个类

反编译类属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.fanshe;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ReflectTest06 {
public static void main(String[] args) throws Exception {
StringBuilder s = new StringBuilder();
Class studentClass = Class.forName("java.lang.Integer"); //
s.append("public class " + studentClass.getSimpleName() + "{\n");

Field[] fields = studentClass.getDeclaredFields();
for(Field field : fields) {
s.append("\t");
s.append(Modifier.toString(field.getModifiers()));
s.append(" ");
s.append(field.getType().getSimpleName());
s.append(" ");
s.append(field.getName());
s.append(";\n");
}

s.append("}");
System.out.println(s);
}
}

反编译类方法的非方法体部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.fanshe;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class ReflectTest09 {
public static void main(String[] args) throws Exception {
StringBuilder s = new StringBuilder();
Class userServiceClass = Class.forName("java.lang.String");
s.append(Modifier.toString(userServiceClass.getModifiers()) + " class "
+ userServiceClass.getSimpleName() + "{\n");
Method[] methods = userServiceClass.getDeclaredMethods();
for(Method method : methods) {
s.append("\t");
s.append(Modifier.toString(method.getModifiers()));
s.append(" ");
s.append(method.getReturnType().getSimpleName());
s.append(" ");
s.append(method.getName());
s.append("(");
Class[] parameterTypes = method.getParameterTypes();
for(Class parameterType : parameterTypes) {
s.append(parameterType.getSimpleName());
s.append(",");
}
s.deleteCharAt(s.length() - 1);


s.append("){}\n");
}

s.append("}");
System.out.println(s);
}
}

反编译构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.fanshe;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

public class ReflectTest11 {
public static void main(String[] args) throws Exception {
StringBuilder s = new StringBuilder();
Class vipClass = Class.forName("java.lang.String");
s.append(Modifier.toString(vipClass.getModifiers()));
s.append(" class ");
s.append(vipClass.getSimpleName());
s.append("{\n");

//拼接构造方法
Constructor[] constructors = vipClass.getDeclaredConstructors();
for(Constructor constructor : constructors) {
s.append("\t");
s.append(Modifier.toString(constructor.getModifiers()));
s.append(" ");
s.append(vipClass.getSimpleName());
s.append("(");
//拼接参数
Class[] parameterTypes = constructor.getParameterTypes();
for(Class paraterType : parameterTypes) {
s.append(paraterType.getSimpleName());
s.append(",");
}
if(parameterTypes.length > 0)
s.deleteCharAt(s.length() - 1);

s.append("){}\n");
}


s.append("}");
System.out.println(s);
}
}

求大佬赏个饭