标签:java
Java提供了强大的反射机制,可以通过Class类获取任何的字段,方法,构造函数,并对它们进行修改或者调用。下面的例子演示了怎么通过java.lang.reflect包下的类获得String类的所有字段,构造函数,方法。
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
public class Reflection {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
Class<String> string = String.class;
Field[] fields = string.getDeclaredFields();
Method[] methods = string.getDeclaredMethods();
Constructor[] constructors = string.getConstructors();
String name = "";
String typeName = "";
String visibility = "";
System.out.println("------------Field-------------------------");
// 遍历字段,打印出它的作用域,限定词,字段名
for (Field f : fields) {
visibility = f.getGenericType().getTypeName();
name = f.getName();
typeName = f.getType().getTypeName();
visibility = isVisibility(f.getModifiers());
System.out.println(visibility + typeName + " " + name + ";");
}
String returnType = "";
String params = "";
System.out.println("-----------constructor----------------------------");
// 遍历构造函数
for (Constructor c : constructors) {
visibility = isVisibility(c.getModifiers());
name = c.getName();
params= getParams(c.getParameters());
System.out.println(visibility + name + " ("
+ params + ") ");
}
System.out.println("-----------method----------------------------------");
// 遍历函数,打印出它的作用域,返回类型,函数名,传递的参数
for (Method m : methods) {
name = m.getName();
returnType = m.getReturnType().getTypeName();
params = getParams(m.getParameters());
visibility = isVisibility(m.getModifiers());
System.out.println(visibility + returnType + " " + name + " ("
+ params + ") ");
}
}
private static String getParams(Parameter[] parameters) {
// TODO Auto-generated method stub
String params = "";
for (Parameter p : parameters) {
params += p.getType().getTypeName() + " " + p.getName() + ",";
}
if (params.length() > 0)
params = params.substring(0, params.length() - 1);
return params;
}
/**
* 查询字段或方法的访问权限
*
* @param modifiers
* @return 字段/方法的作用域
*/
private static String isVisibility(int modifiers) {
// TODO Auto-generated method stub
String visibility = "";
if (Modifier.isPrivate(modifiers)) {
visibility += "private ";
}
if (Modifier.isProtected(modifiers)) {
visibility += "protected ";
}
if (Modifier.isPublic(modifiers)) {
visibility += "public ";
}
if (Modifier.isAbstract(modifiers)) {
visibility += "abstract ";
}
if (Modifier.isStatic(modifiers)) {
visibility += "static ";
}
if (Modifier.isFinal(modifiers)) {
visibility += "final ";
}
if (Modifier.isNative(modifiers)) {
visibility += "native ";
}
if (Modifier.isVolatile(modifiers)) {
visibility += "volatile ";
}
if (Modifier.isSynchronized(modifiers)) {
visibility += "synchronized ";
}
if (Modifier.isTransient(modifiers)) {
visibility += "transient ";
}
return visibility;
}
}
标签:java
原文地址:http://blog.csdn.net/u013769320/article/details/45273355