一个小巧方便的java反射工具

对lukas eder写的reflect做了一些扩展, 使其更强大, 满足自己的使用场景.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715

/**
* Copyright (c) 2011-2012, Lukas Eder, lukas.eder@gmail.com
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOR" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.*;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

/**
*
* 为了满足自己的需求, 支持对私有属性和方法进行反射, 包括一直向上父类查找方法或属性, 因为完全暴露了方法和属性, 谨慎使用
*
* A wrapper for an {@link Object} or {@link Class} upon which reflective calls
* can be made.
* <p>
* An example of using <code>Reflect</code> is <code><pre>
* // Static import all reflection methods to decrease verbosity
* import static org.joor.Reflect.*;
*
* // Wrap an Object / Class / class name with the on() method:
* on("java.lang.String")
* // Invoke constructors using the create() method:
* .create("Hello World")
* // Invoke methods using the call() method:
* .call("toString")
* // Retrieve the wrapped object
*
* @author Lukas Eder
*/

public class Reflect {
private final static Logger logger = LoggerFactory.getLogger(Reflect.class);

public static class Param<T>{
Class<?> type;
T value;
public Param(String name, T value) {
Class<?> type = null;
try {
type = Class.forName(name);
} catch (ClassNotFoundException e) {
throw new RuntimeException("class name:" + name, e);
}
this.type = type;
this.value = value;
}

public Param(Class<?> type, T value) {
super();
this.type = type;
this.value = value;
}
public Param<T> type(Class<?> type){
this.type = type;
return this;
}
public Param<T> value(T value){
this.value = value;
return this;
}
}


// ---------------------------------------------------------------------
// Static API used as entrance points to the fluent API
// ---------------------------------------------------------------------

/**
* Wrap a class name.
* <p>
* This is the same as calling <code>on(Class.forName(name))</code>
*
* @param name A fully qualified class name
* @return A wrapped class object, to be used for further reflection.
*
* @see #on(Class)
*/

public static Reflect on(String name) {
return on(forName(name));
}

/**根据类名称构造实例*/
public static Reflect instance(String name) {
Object o;
try {
o = forName(name).newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
return on(o);
}

/**
* Wrap a class.
* <p>
* Use this when you want to access static fields and methods on a
* {@link Class} object, or as a basis for constructing objects of that
* class using {@link #create(Object...)}
*
* @param clazz The class to be wrapped
* @return A wrapped class object, to be used for further reflection.
*/

public static Reflect on(Class<?> clazz) {
return new Reflect(clazz);
}

/**
* Wrap an object.
* <p>
* Use this when you want to access instance fields and methods on any
* {@link Object}
*
* @param object The object to be wrapped
* @return A wrapped object, to be used for further reflection.
*/

public static Reflect on(Object object) {
return new Reflect(object);
}

/**
* Conveniently render an {@link java.lang.reflect.AccessibleObject} accessible
*
* @param accessible The object to render accessible
* @return The argument object rendered accessible
*/

public static <T extends AccessibleObject> T accessible(T accessible) {
if (accessible == null) {
return null;
}

if (!accessible.isAccessible()) {
accessible.setAccessible(true);
}

return accessible;
}

// ---------------------------------------------------------------------
// Members
// ---------------------------------------------------------------------

/**
* The wrapped object
*/

private final Object object;

/**
* A flag indicating whether the wrapped object is a {@link Class} (for
* accessing static fields and methods), or any other type of {@link Object}
* (for accessing instance fields and methods).
*/

private final boolean isClass;


// ---------------------------------------------------------------------
// Constructors
// ---------------------------------------------------------------------

private Reflect(Class<?> type) {
this.object = type;
this.isClass = true;
}

private <T> Reflect(T object) {
this.object = object;
this.isClass = false;
}

// ---------------------------------------------------------------------
// Fluent Reflection API
// ---------------------------------------------------------------------

/**
* Get the wrapped object
*
* @param <T> A convenience generic parameter for automatic unsafe casting
*/

@SuppressWarnings("unchecked")
public <T> T get() {
return (T) object;
}

/**
* Set a field value.
* <p>
* This is roughly equivalent to {@link java.lang.reflect.Field#set(Object, Object)}. If the
* wrapped object is a {@link Class}, then this will set a value to a static
* member field. If the wrapped object is any other {@link Object}, then
* this will set a value to an instance member field.
*
* @param name The field name
* @param value The new field value
* @return The same wrapped object, to be used for further reflection.
*
*/

public Reflect set(String name, final Object value) {
return doExecute(name, new Executor() {
@Override
public Reflect execute(Field field)throws Exception {
field.set(object, unwrap(value));
return on(object);
}});
}

/**
* Get a field value.
* <p>
* This is roughly equivalent to {@link java.lang.reflect.Field#get(Object)}. If the wrapped
* object is a {@link Class}, then this will get a value from a static
* member field. If the wrapped object is any other {@link Object}, then
* this will get a value from an instance member field.
* <p>
* If you want to "navigate" to a wrapped version of the field, use
* {@link #field(String)} instead.
*
* @param name The field name
* @return The field value
*
* @see #field(String)
*/

public <T> T get(String name) {
return field(name).<T>get();
}

interface Executor{
Reflect execute(Field field)throws Exception;
}

/**
* Get a wrapped field.
* <p>
* This is roughly equivalent to {@link java.lang.reflect.Field#get(Object)}. If the wrapped
* object is a {@link Class}, then this will wrap a static member field. If
* the wrapped object is any other {@link Object}, then this wrap an
* instance member field.
*
* @param name The field name
* @return The wrapped field
*
*/

public Reflect field(String name) {
return doExecute(name, new Executor() {
@Override
public Reflect execute(Field field)throws Exception {
return on(field.get(object));
}});
}

private Reflect doExecute(String name, Executor executor) {
Class<?> useClazz = type();
Field field = null;
do {
try {
field = useClazz.getDeclaredField(name);
field = accessible(field);
return executor.execute(field);
} catch (NoSuchFieldException e) {
//
} catch (Exception e) {
throw new RuntimeException("class:" + useClazz + ", name:" + name, e);
}
if (field == null) {
useClazz = useClazz.getSuperclass();
}
} while (useClazz != null);

throw new RuntimeException("don't execute on field[" + name + "]");
}

/**
* Get a Map containing field names and wrapped values for the fields'
* values.
* <p>
* If the wrapped object is a {@link Class}, then this will return static
* fields. If the wrapped object is any other {@link Object}, then this will
* return instance fields.
* <p>
* These two calls are equivalent <code><pre>
* on(object).field("myField");
* on(object).fields().get("myField");
* </pre></code>
*
* @return A map containing field names and wrapped values.
*/

public Map<String, Reflect> fields() {
Map<String, Reflect> result = new LinkedHashMap<String, Reflect>();

for (Field field : type().getFields()) {
if (!isClass ^ Modifier.isStatic(field.getModifiers())) {
String name = field.getName();
result.put(name, field(name));
}
}

return result;
}

/**
* Call a method by its name.
* <p>
* This is a convenience method for calling
* <code>call(name, new Object[0])</code>
*
* @param name The method name
* @return The wrapped method result or the same wrapped object if the
* method returns <code>void</code>, to be used for further
* reflection.
*
* @see #call(String, Object...)
*/

public Reflect call(String name) {
return call(name, new Object[0]);
}

/**
* Call a method by its name.
* <p>
* This is roughly equivalent to {@link java.lang.reflect.Method#invoke(Object, Object...)}.
* If the wrapped object is a {@link Class}, then this will invoke a static
* method. If the wrapped object is any other {@link Object}, then this will
* invoke an instance method.
* <p>
* Just like {@link java.lang.reflect.Method#invoke(Object, Object...)}, this will try to wrap
* primitive types or unwrap primitive type wrappers if applicable. If
* several methods are applicable, by that rule, the first one encountered
* is called. i.e. when calling <code><pre>
* on(...).call("method", 1, 1);
* </pre></code> The first of the following methods will be called:
* <code><pre>
* public void method(int param1, Integer param2);
* public void method(Integer param1, int param2);
* public void method(Number param1, Number param2);
* public void method(Number param1, Object param2);
* public void method(int param1, Object param2);
* </pre></code>
*
* @param name The method name
* @param args The method arguments
* @return The wrapped method result or the same wrapped object if the
* method returns <code>void</code>, to be used for further
* reflection.
*
*/

public Reflect call(String name, Object... args) {
//return doCall(name, types(args), args);
Class<?>[] types;
Object[] values = null;
if (args == null) {
types = new Class[0];
}else {
types = new Class[args.length];

for (int i = 0; i < args.length; i++) {
Object arg = args[i];
types[i] = (arg instanceof Param) ? ((Param)arg).type : arg.getClass();
}

values = new Object[args.length];
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
values[i] = (arg instanceof Param) ? ((Param)arg).value : arg;
}
}

return doCall(name, types, values);
}

public static <T> Param<T> param(Class<?> type, T value) {
return new Param<T>(type, value);
}

private Reflect doCall(String name, Class<?>[] types, Object[] values) {
Class<?> clazz = type();
Method method = null;
do {
try {
method = clazz.getDeclaredMethod(name, types);
return on(method, object, values);
} catch (NoSuchMethodException e) {
logger.warn("class:" + clazz.getName() + ", mehtod:" + name + "(" + Arrays.toString(types) + ")", e);
} catch (Exception e) {
throw new RuntimeException("class:" + clazz.getName() + ", method:" + name + "(" + Arrays.toString(types) + ")", e);
}
if (method == null) {
clazz = clazz.getSuperclass();
}
} while (clazz != null);

throw new RuntimeException("don't execute the method " + type() + "." + name + "(" + Arrays.toString(values) + ")");
}

/**
* Call a constructor.
* <p>
* This is a convenience method for calling
* <code>create(new Object[0])</code>
*
* @return The wrapped new object, to be used for further reflection.
*
* @see #create(Object...)
*/

public Reflect create() {
return create(new Object[0]);
}

/**
* Call a constructor.
* <p>
* This is roughly equivalent to {@link java.lang.reflect.Constructor#newInstance(Object...)}.
* If the wrapped object is a {@link Class}, then this will create a new
* object of that class. If the wrapped object is any other {@link Object},
* then this will create a new object of the same type.
* <p>
* Just like {@link java.lang.reflect.Constructor#newInstance(Object...)}, this will try to
* wrap primitive types or unwrap primitive type wrappers if applicable. If
* several constructors are applicable, by that rule, the first one
* encountered is called. i.e. when calling <code><pre>
* on(C.class).create(1, 1);
* </pre></code> The first of the following constructors will be applied:
* <code><pre>
* public C(int param1, Integer param2);
* public C(Integer param1, int param2);
* public C(Number param1, Number param2);
* public C(Number param1, Object param2);
* public C(int param1, Object param2);
* </pre></code>
*
* @param args The constructor arguments
* @return The wrapped new object, to be used for further reflection.
*
*/

public Reflect create(Object... args) {
Class<?>[] types = types(args);

return doCreate(types, args);
}

public Reflect create(Param<?>... args) {
Class<?>[] types = null;
Object[] values = null;
if (args == null) {
types = new Class[0];
}else {
types = new Class[args.length];

for (int i = 0; i < args.length; i++) {
types[i] = args[i].type;
}

values = new Object[args.length];
for (int i = 0; i < args.length; i++) {
values[i] = args[i].value;
}
}

return doCreate(types, values);
}

private Reflect doCreate(Class<?>[] types, Object... args) {
// Try invoking the "canonical" constructor, i.e. the one with exact
// matching argument types
try {
Constructor<?> constructor = type().getConstructor(types);
return on(constructor, args);
}

// If there is no exact match, try to find one that has a "similar"
// signature if primitive argument types are converted to their wrappers
catch (NoSuchMethodException e) {
for (Constructor<?> constructor : type().getDeclaredConstructors()) {
if (match(constructor.getParameterTypes(), types)) {
return on(constructor, args);
}
}

throw new RuntimeException(e);
}
}

/**
* Create a proxy for the wrapped object allowing to typesafely invoke
* methods on it using a custom interface
*
* @param proxyType The interface type that is implemented by the proxy
* @return A proxy for the wrapped object
*/

@SuppressWarnings("unchecked")
public <P> P as(Class<P> proxyType) {
final InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return on(object).call(method.getName(), args).get();
}
};

return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[] { proxyType }, handler);
}

// ---------------------------------------------------------------------
// Object API
// ---------------------------------------------------------------------

/**
* Check whether two arrays of types match, converting primitive types to
* their corresponding wrappers.
*/

private boolean match(Class<?>[] declaredTypes, Class<?>[] actualTypes) {
if (declaredTypes.length == actualTypes.length) {
for (int i = 0; i < actualTypes.length; i++) {
if (!wrapper(declaredTypes[i]).isAssignableFrom(wrapper(actualTypes[i]))) {
return false;
}
}

return true;
}
else {
return false;
}
}

/**
* {@inheritDoc}
*/

@Override
public int hashCode() {
return object.hashCode();
}

/**
* {@inheritDoc}
*/

@Override
public boolean equals(Object obj) {
if (obj instanceof Reflect) {
return object.equals(((Reflect) obj).get());
}

return false;
}

/**
* {@inheritDoc}
*/

@Override
public String toString() {
return object.toString();
}

// ---------------------------------------------------------------------
// Utility methods
// ---------------------------------------------------------------------

/**
* Wrap an object created from a constructor
*/

private static Reflect on(Constructor<?> constructor, Object... args) {
try {
constructor = accessible(constructor);
return on(constructor.newInstance(args));
}
catch (Exception e) {
throw new RuntimeException(e);
}
}

/**
* Wrap an object returned from a method
*/

private static Reflect on(Method method, Object object, Object... args) {
try {
accessible(method);

if (method.getReturnType() == void.class) {
method.invoke(object, args);
return on(object);
}
else {
return on(method.invoke(object, args));
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}

/**
* Unwrap an object
*/

private static Object unwrap(Object object) {
if (object instanceof Reflect) {
return ((Reflect) object).get();
}

return object;
}

/**
* Get an array of types for an array of objects
*
* @see Object#getClass()
*/

private static Class<?>[] types(Object... values) {
if (values == null) {
return new Class[0];
}

Class<?>[] result = new Class[values.length];

for (int i = 0; i < values.length; i++) {
result[i] = values[i].getClass();
}

return result;
}

/**
* Load a class
*
* @see Class#forName(String)
*/

private static Class<?> forName(String name) {
try {
return Class.forName(name);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}

/**
* Get the type of the wrapped object.
*
* @see Object#getClass()
*/

public Class<?> type() {
if (isClass) {
return (Class<?>) object;
}
else {
return object.getClass();
}
}

/**
* Get a wrapper type for a primitive type, or the argument type itself, if
* it is not a primitive type.
*/

private static Class<?> wrapper(Class<?> type) {
if (boolean.class == type) {
return Boolean.class;
}
else if (int.class == type) {
return Integer.class;
}
else if (long.class == type) {
return Long.class;
}
else if (short.class == type) {
return Short.class;
}
else if (byte.class == type) {
return Byte.class;
}
else if (double.class == type) {
return Double.class;
}
else if (float.class == type) {
return Float.class;
}
else if (char.class == type) {
return Character.class;
}
else {
return type;
}
}

}