代码片段: javase-gistfile1.txt

import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Scanner; public cl...
<pre>import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Scanner; public class TestReflection { public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { String className = null; Scanner scan = null; if(args.length > 0) className = args[0]; else { scan = new Scanner(System.in); className = scan.next(); Class<?> cl = Class.forName(className); Class<?> su = cl.getSuperclass(); String modifier = Modifier.toString(cl.getModifiers()); if(modifier.length() > 0) System.out.print(modifier + " "); System.out.print("class " + cl.getName()); if(su != null && su != Object.class) System.out.print(" extends " + su.getName()); System.out.println(" {"); printFields(Double.class); System.out.println(); printConstructor(Double.class); System.out.println(); printMethods(Double.class); System.out.println("}"); } } public static void printConstructor(Class<?> cl) { Constructor<?>[] constructors = cl.getDeclaredConstructors(); for(Constructor<?> constructor : constructors) { String modifier = Modifier.toString(constructor.getModifiers()); if(modifier.length() > 0) System.out.print(" " + modifier + " "); System.out.print(cl.getName() + "("); Class<?>[] parameterTypes = constructor.getParameterTypes(); for(int i = 0; i < parameterTypes.length; i++) { if(i > 0) System.out.print(", "); System.out.print(parameterTypes[i].getName()); } System.out.println(");"); } } public static void printMethods(Class<?> cl) { Method[] methods = cl.getDeclaredMethods(); for (Method method : methods) { String modifier = Modifier.toString(method.getModifiers()); if(modifier.length() > 0) System.out.print(" " + modifier + " "); Class<?> returnType = method.getReturnType(); System.out.print(returnType.getName() + " " + method.getName() + "("); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { if(i > 0) System.out.print(", "); System.out.print(parameterTypes[i].getName()); } System.out.println(");"); } } public static void printFields(Class<?> cl) { Field[] fields = cl.getFields(); for (Field field : fields) { String modifier = Modifier.toString(field.getModifiers()); if(modifier.length() > 0) System.out.print(" " + modifier + " "); Class<?> type = field.getType(); String name = field.getName(); System.out.println(type + " " + name + ";"); } } } </pre>
  • 发表于 2018-07-07 22:00
  • 阅读 ( 776 )
  • 分类:代码片段

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除