[java] 深入理解内部类: inner-classes(二)
ing
Student.class:
https://www.cppentry.com/upload_files/article/76/1_4fwdi__.jpg #student
从Student$Counting.class中发现, 它的构造函数的参数列表中多了一个变量:
// before
public Counting(int paramInt) {
this.step = paramInt;
this.num = 1;
}
// after
public Student$Counting(Student paramStudent, int paramInt) {
// ...
}
但是仍然没有可视化的给出, 到底将这个变量赋值给了谁 尝试的寻找更合适的java反向编译的软件, 花了近2个多小时的时间, 没有找到合适的, 哎, 算了, 反正不是为了得到反向的所有的代码, 只是专注于类内部的成员变量以及成员函数, 就采用java.lang.reflect中的类实现了从一个class文件中提取类名, 成员变量以及函数的.
3.1 从类文件中提取成员函数, 变量以及构造函数
在reflect库中包含了一下三个类Field, Method, Constructor用来分别获得和成员变量, 成员函数, 以及构造函数相关的内容. 具体实现如下1:
import java.lang.reflect.*;
import javax.swing.*;
public class ReflectionTest {
public static void main(String[] args) {
// 从命令行中输入待处理文件, 或是由用户输入
String name;
if (args.length > 0)
name = args[0];
else
name = JOptionPane.showInputDialog
("Class name (e.g. java.util.Date): ");
try {
// 输出类名以及父类
Class cl = Class.forName(name);
Class supercl = cl.getSuperclass();
System.out.print("class " + name);
if (supercl != null && supercl != Object.class) {
System.out.print(" extends " + supercl.getName());
}
System.out.print(" {\n");
printConstructors(cl);
System.out.println();
printMethods(cl);
System.out.println();
printFields(cl);
System.out.println("}");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
*/
public static void printConstructors(Class cl) {
Constructor[] constructors = cl.getDeclaredConstructors();
for (int i = 0; i < constructors.length; i++) {
Constructor c = constructors[i];
String name = c.getName();
System.out.print("\t" + Modifier.toString(c.getModifiers()));
System.out.print(" " + name + "(");
// 输出参数类型
Class[] paramTypes = c.getParameterTypes();
for (int j = 0; j < paramTypes.length; j++) {
if (j > 0) System.out.print(", ");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
/**
输出一个类的所有成员方法
*/
public static void printMethods(Class cl) {
Method[] methods = cl.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
Class retType = m.getReturnType();
String name = m.getName();
System.out.print("\t" + Modifier.toString(m.getModifiers()));
System.out.print(" " + retType.getName() + " " + name + "(");
// 输出参数类型
Class[] paramTypes = m.getParameterTypes();
for (int j = 0; j < paramTypes.length; j++) {
if (j > 0) System.out.print(", ");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
/**
输出所有的成员变量
*/
public static void printFields(Class cl) {
Field[] fields = cl.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
Class type = f.getType();
String name = f.getName();
System.out.print("\t" + Modifier.toString(f.getModifiers()));