学完反射后做的简单的自动实例化项目?

JAVA学习网 2021-03-12 22:13:01
  1 import java.lang.annotation.*;
  2 import java.lang.reflect.Array;
  3 import java.lang.reflect.Constructor;
  4 import java.lang.reflect.InvocationTargetException;
  5 import java.lang.reflect.Method;
  6 import java.util.*;
  7 
  8 public class TestAnnotation {
  9     static int count = 0;
 10 
 11     public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException, ClassNotFoundException {
 12         String annoName = "hahah";
 13         String[] a = new String[10];
 14         System.out.println(a.toString());
 15         testClass("Student", annoName);
 16     }
 17 
 18     public static void testClass(String className, String annoName) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException {
 19         System.out.println();
 20         System.out.println("开始定位:" + className);
 21         Class c = Class.forName(className);
 22         Class cCopy =c;
 23         if (c.getAnnotation(Class.forName(annoName)) != null) {
 24             System.out.println("该类带有注解" + annoName + ",开始实例化测试。");
 25             Constructor[] declaredConstructors = c.getDeclaredConstructors();
 26 
 27             for (Constructor constructor :declaredConstructors) {
 28                 System.out.print("构造器为:");
 29                 System.out.println(constructor);
 30                 Method[][] methods = getMethods(c);
 31                 Object o = getInstance(constructor);
 32                 runMethods(o,methods);
 33             }
 34         } else {
 35             System.out.println("该类未被" + annoName + "注解,不进行实例测试。");
 36         }
 37     }
 38     public static Method[][] getMethods(Class c) throws InvocationTargetException, IllegalAccessException, InstantiationException, ClassNotFoundException {
 39         Method[] methods = c.getDeclaredMethods();
 40         ArrayList<Method> methodsVoid = new ArrayList<Method>();
 41         ArrayList<Method> methodsOthers = new ArrayList<Method>();
 42         //将方法分为有返回方法和无返回方法,有返回方法前后各执行一次,无返回方法中间执行一遍。
 43         for (Method method : methods) {
 44             if (method.getReturnType().toString().equals("void")) {
 45                 methodsVoid.add(method);
 46             } else {
 47                 methodsOthers.add(method);
 48             }
 49         }
 50         while(true){
 51             c = c.getSuperclass();
 52             if(c.getName().equals("java.lang.Object")){
 53                 break;
 54             }else{
 55                 methods = c.getDeclaredMethods();
 56                 //将方法分为有返回方法和无返回方法,有返回方法前后各执行一次,无返回方法中间执行一遍。
 57                 for (Method method : methods) {
 58                     if (method.getReturnType().toString().equals("void")) {
 59                         methodsVoid.add(method);
 60                     } else {
 61                         methodsOthers.add(method);
 62                     }
 63                 }
 64             }
 65         }
 66 
 67         return new Method[][]{methodsVoid.toArray(new Method[methodsVoid.size()]),methodsOthers.toArray(new Method[methodsOthers.size()])};
 68     }
 69 
 70     public static void runMethods(Object o, Method[][] methods) throws InvocationTargetException, IllegalAccessException, InstantiationException, ClassNotFoundException {
 71         for (Method method : methods[1]) {
 72             System.out.println(method);
 73             System.out.print("方法:" + method.getName() + "  ");
 74             System.out.print("参数为:");
 75             ArrayList argsList = getArgus(method);
 76             System.out.println(argsList);
 77             System.out.println(argsList.toString());
 78             System.out.print("返回结果:");
 79             System.out.println(method.invoke(o, argsList.toArray()));
 80         }
 81         for (Method method : methods[0]) {
 82             System.out.print("方法:" + method.getName() + "  ");
 83             System.out.print("参数为:");
 84             ArrayList argsList = getArgus(method);
 85             System.out.println(argsList.toString());
 86             System.out.print("返回结果:");
 87             System.out.println(method.invoke(o, argsList.toArray()));
 88         }
 89         for (Method method : methods[1]) {
 90             System.out.print("方法:" + method.getName() + "  ");
 91             System.out.print("参数为:");
 92             ArrayList argsList = getArgus(method);
 93             System.out.println(argsList.toString());
 94             System.out.print("返回结果:");
 95             System.out.println(method.invoke(o, argsList.toArray()));
 96         }
 97     }
 98 
 99     public static ArrayList getArgus(Method method) throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
100         Class[] parameters = method.getParameterTypes();
101         ArrayList argsList = new ArrayList();
102         if (parameters.length > 0) {
103             for (Class parameter : parameters) {
104                 argsList.add(getArgu(parameter));
105             }
106         }
107         return argsList;
108     }
109     //重载一下
110     public static Object[] getArgus(Constructor constructor) throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
111         Class[] parameters = constructor.getParameterTypes();
112         List argsList = new ArrayList();
113         if (parameters.length > 0) {
114             for (Class parameter : parameters) {
115                 argsList.add(getArgu(parameter));
116             }
117         }
118         return argsList.toArray();
119     }
120 
121 
122     public static Object getArgu(Class parameter) throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
123         if (parameter.isArray()) {
124             int num = 10;
125             Class pp = parameter.getComponentType();
126             Object list = Array.newInstance(pp,num);
127             for (int i = 0; i < num; i++) {
128                 Array.set(list,i,getArgu(pp));//数组对象递归初始化参数
129             }
130             return list;
131         } else {
132             String[] p = parameter.getName().split("\\.");
133             String pp = p[p.length - 1];
134             if (pp.equals("String")) {
135                 int num = new Random().nextInt(10) + 1;
136                 return getRandomString(num);
137             } else if (pp.equals("int")) {
138                 return getRandomInt(100);
139             } else if (pp.equals("byte")) {
140                 return getRandomByte();
141             } else if (pp.equals("short")) {
142                 return getRandomShort();
143             } else if (pp.equals("long")) {
144                 return getRandomLong();
145             } else if (pp.equals("float")) {
146                 return getRandomFloat();
147             } else if (pp.equals("double")) {
148                 return getRandomDouble();
149             } else if (pp.equals("char")) {
150                 return getRandomChar();
151             } else {
152                 return getInstance(pp);
153 
154             }
155         }
156     }
157     public static Object getInstance(String className) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException {
158         Class c = Class.forName(className);
159         Constructor[] constructors = c.getDeclaredConstructors();
160         Constructor constructor = constructors[count++ % constructors.length];
161         return getInstance(constructor);
162     }
163 
164     public static Object getInstance(Constructor constructor) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException {
165 //        Constructor constructor = constructors[new Random().nextInt(constructors.length)];
166 //        System.out.println(constructor);
167         return constructor.newInstance(getArgus(constructor));
168     }
169 
170     public static String getRandomString(int length) {
171         String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
172         Random random = new Random();
173         StringBuffer sb = new StringBuffer();
174         for (int i = 0; i < length; i++) {
175             int number = random.nextInt(62);
176             sb.append(str.charAt(number));
177         }
178         return sb.toString();
179     }
180 
181     public static int getRandomInt(int max) {
182         int a = new Random().nextInt(max);
183         if (getRandomBoolean()){
184             a = - a;
185         }
186         return a;
187     }
188     public static int getRandomInt() {
189         int a = getRandomInt(Integer.MAX_VALUE);
190         return a;
191     }
192     public static byte getRandomByte() {
193         return (byte)getRandomInt(Byte.MAX_VALUE);
194     }
195     public static short getRandomShort() {
196         return (short)getRandomInt(Short.MAX_VALUE);
197     }
198     public static long getRandomLong() {
199         long a = new Random().nextLong();
200         if (getRandomBoolean()){
201             a = - a;
202         }
203         return a;
204     }
205     public static float getRandomFloat() {
206         float a = new Random().nextFloat();
207         if (getRandomBoolean()){
208             a = - a;
209         }
210         return a;
211     }
212     public static double getRandomDouble() {
213         double a = new Random().nextDouble();
214         if (getRandomBoolean()){
215             a = - a;
216         }
217         return a;
218     }
219     public static boolean getRandomBoolean(){
220         return new Random().nextBoolean();
221     }
222     public static char getRandomChar(){
223         return (char) getRandomInt(Character.MAX_VALUE);
224     }
225 
226 }
227 //文件类的get就不弄了,可以动态生成各个类型文件,或者弄些文件夹,每个文件夹一种类型,把文件都放进去,然后随机获取。 228 @Target(ElementType.TYPE) 229 @Retention(RetentionPolicy.RUNTIME) 230 @interface hahah { 231 } 232 233 234 class Person { 235 String name; 236 int age; 237 238 public Person() { 239 240 } 241 242 public Person(String name, int age) { 243 this.name = name; 244 this.age = age; 245 } 246 247 public String getName() { 248 return name; 249 } 250 251 public void setName(String name, Test t, int[] ha,String[] s,Student[] st) { 252 this.name = name; 253 } 254 255 public int getAge() { 256 return age; 257 } 258 259 public void setAge(int age) { 260 this.age = age; 261 } 262 263 @Override 264 public String toString() { 265 return "Person{" + 266 "name='" + name + '\'' + 267 ", age=" + age + 268 '}'; 269 } 270 } 271 @hahah 272 class Student extends Person{ 273 public void pr(){ 274 System.out.println("hhaha"); 275 } 276 } 277 278 class Test { 279 280 }

 

阅读(869) 评论(0)