package com.reflect; |
import java.lang.reflect.Constructor; |
import java.lang.reflect.Field; |
import java.lang.reflect.Method; |
import java.lang.reflect.Modifier; |
import javax.swing.JFrame; |
import javax.swing.JOptionPane; |
import javax.swing.JTextArea; |
/** |
* |
* This program uses reflection to all information of a class |
* |
* @version 2014-7-1 |
* |
*/ |
@SuppressWarnings ( "rawtypes" ) |
public class Reflect { |
private JTextArea textArea; |
private JFrame frame; |
public void link_frame(Reflect_UI frame) { |
this .frame = frame; |
this .textArea = frame.getTextArea(); |
} |
public void EnterClassName(String className) { |
try { |
Class c = Class.forName(className); |
printClass(c); |
textArea.append( "\n{\n" ); |
textArea.append( "\n// fields\n" ); |
printFields(c); |
textArea.append( "\n// constructors\n" ); |
printConstructors(c); |
textArea.append( "\n//methods \n" ); |
printMethods(c); |
textArea.append( "\n}\n" ); |
} catch (ClassNotFoundException e) { |
e.printStackTrace(); |
JOptionPane.showMessageDialog(frame, "ClassNotFoundException" ); |
} |
} |
// print Class |
private void printClass(Class c) { |
Class superC = c.getSuperclass(); |
// print modifiers of class |
textArea.append(Modifier.toString(c.getModifiers()) + " " + "class " ); |
textArea.append(c.getName() + " " ); |
// "superC!=null" 对于Object类 |
if (superC != null && superC != Object. class ) { |
textArea.append( "extends " + superC.getName()); |
} |
} |
// print DeclaredFields |
private void printFields(Class c) { |
Field[] fields = c.getDeclaredFields(); |
for (Field f : fields) { |
textArea.append(Modifier.toString(f.getModifiers()) + " " |
+ f.getType().getName() + " " + f.getName() + "\n" ); |
} |
} |
// print DeclaredConstructors |
private void printConstructors(Class c) { |
Constructor[] constructors = c.getDeclaredConstructors(); |
for (Constructor con : constructors) { |
textArea.append(Modifier.toString(con.getModifiers()) + " " |
+ con.getName() + " (" ); |
int i = 0 ; |
for (Class par : con.getParameterTypes()) { |
if (i > 0 ) |
textArea.append( ", " ); |
textArea.append(par.getTypeName()); |
i++; |
} |
textArea.append( ")\n" ); |
} |
} |
// print DeclaredMethods |
private void printMethods(Class c) { |
Method[] methods = c.getDeclaredMethods(); |
for (Method m : methods) { |
textArea.append(Modifier.toString(m.getModifiers()) + " " |
+ m.getReturnType().getName() + " " + m.getName() + " (" ); |
int i = 0 ; |
for (Class par : m.getParameterTypes()) { |
if (i > 0 ) |
textArea.append( ", " ); |
textArea.append(par.getTypeName()); |
i++; |
} |
textArea.append( ")\n" ); |
} |
} |
} |
//源代码片段来自云代码http://yuncode.net |
|