/
ClassMeta.java
2085 lines (1900 loc) · 68.1 KB
/
ClassMeta.java
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ***************************************************************************************************************************
// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
// * with the License. You may obtain a copy of the License at *
// * *
// * http://www.apache.org/licenses/LICENSE-2.0 *
// * *
// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an *
// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the *
// * specific language governing permissions and limitations under the License. *
// ***************************************************************************************************************************
package org.apache.juneau;
import static org.apache.juneau.ClassMeta.ClassCategory.*;
import static org.apache.juneau.internal.ClassUtils.*;
import static org.apache.juneau.internal.ObjectUtils.*;
import static org.apache.juneau.reflect.ReflectFlags.*;
import java.io.*;
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.lang.reflect.Proxy;
import java.net.*;
import java.net.URI;
import java.time.temporal.*;
import java.util.*;
import java.util.Date;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import org.apache.juneau.annotation.*;
import org.apache.juneau.collections.*;
import org.apache.juneau.http.*;
import org.apache.juneau.json.*;
import org.apache.juneau.reflect.*;
import org.apache.juneau.transform.*;
/**
* A wrapper class around the {@link Class} object that provides cached information about that class.
*
* <p>
* Instances of this class can be created through the {@link BeanContext#getClassMeta(Class)} method.
*
* <p>
* The {@link BeanContext} class will cache and reuse instances of this class except for the following class types:
* <ul>
* <li>Arrays
* <li>Maps with non-Object key/values.
* <li>Collections with non-Object key/values.
* </ul>
*
* <p>
* This class is tied to the {@link BeanContext} class because it's that class that makes the determination of what is
* a bean.
*
* @param <T> The class type of the wrapped class.
*/
@Bean(bpi="innerClass,classCategory,elementType,keyType,valueType,notABeanReason,initException,beanMeta")
public final class ClassMeta<T> implements Type {
/** Class categories. */
enum ClassCategory {
MAP, COLLECTION, CLASS, METHOD, NUMBER, DECIMAL, BOOLEAN, CHAR, DATE, ARRAY, ENUM, OTHER, CHARSEQ, STR, OBJ, URI, BEANMAP, READER, INPUTSTREAM, VOID, ARGS, OPTIONAL
}
final Class<T> innerClass; // The class being wrapped.
final ClassInfo info;
private final Class<? extends T> implClass; // The implementation class to use if this is an interface.
private final ClassCategory cc; // The class category.
private final Method fromStringMethod; // The static valueOf(String) or fromString(String) or forString(String) method (if it has one).
private final ConstructorInfo
noArgConstructor, // The no-arg constructor for this class (if it has one).
stringConstructor; // The X(String) constructor (if it has one).
private final Method
exampleMethod; // The example() or @Example-annotated method (if it has one).
private final Field
exampleField; // The @Example-annotated field (if it has one).
private final Setter
namePropertyMethod, // The method to set the name on an object (if it has one).
parentPropertyMethod; // The method to set the parent on an object (if it has one).
private final boolean
isDelegate, // True if this class extends Delegate.
isAbstract, // True if this class is abstract.
isMemberClass; // True if this is a non-static member class.
private final Object primitiveDefault; // Default value for primitive type classes.
private final Map<String,Method>
publicMethods; // All public methods, including static methods.
private final PojoSwap<?,?>[] childPojoSwaps; // Any PojoSwaps where the normal type is a subclass of this class.
private final ConcurrentHashMap<Class<?>,PojoSwap<?,?>>
childSwapMap, // Maps normal subclasses to PojoSwaps.
childUnswapMap; // Maps swap subclasses to PojoSwaps.
private final PojoSwap<T,?>[] swaps; // The object POJO swaps associated with this bean (if it has any).
private final BuilderSwap<T,?> builderSwap; // The builder swap associated with this bean (if it has one).
private final BeanContext beanContext; // The bean context that created this object.
private final ClassMeta<?>
elementType, // If ARRAY or COLLECTION, the element class type.
keyType, // If MAP, the key class type.
valueType; // If MAP, the value class type.
private final BeanMeta<T> beanMeta; // The bean meta for this bean class (if it's a bean).
private final String
typePropertyName, // The property name of the _type property for this class and subclasses.
notABeanReason, // If this isn't a bean, the reason why.
dictionaryName; // The dictionary name of this class if it has one.
private final Throwable initException; // Any exceptions thrown in the init() method.
private final InvocationHandler invocationHandler; // The invocation handler for this class (if it has one).
private final BeanRegistry beanRegistry; // The bean registry of this class meta (if it has one).
private final ClassMeta<?>[] args; // Arg types if this is an array of args.
private final String example; // Example JSON.
private final Map<Class<?>,Mutater<?,T>> fromMutaters = new ConcurrentHashMap<>();
private final Map<Class<?>,Mutater<T,?>> toMutaters = new ConcurrentHashMap<>();
private final Mutater<String,T> stringMutater;
private final ReadWriteLock lock = new ReentrantReadWriteLock(false);
private final Lock rLock = lock.readLock(), wLock = lock.writeLock();
/**
* Construct a new {@code ClassMeta} based on the specified {@link Class}.
*
* @param innerClass The class being wrapped.
* @param beanContext The bean context that created this object.
* @param implClass
* For interfaces and abstract classes, this represents the "real" class to instantiate.
* Can be <jk>null</jk>.
* @param pojoSwap
* The {@link PojoSwap} programmatically associated with this class.
* Can be <jk>null</jk>.
* @param childPojoSwap
* The child {@link PojoSwap PojoSwaps} programmatically associated with this class.
* These are the <c>PojoSwaps</c> that have normal classes that are subclasses of this class.
* Can be <jk>null</jk>.
* @param delayedInit
* Don't call init() in constructor.
* Used for delayed initialization when the possibility of class reference loops exist.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
ClassMeta(Class<T> innerClass, BeanContext beanContext, Class<? extends T> implClass, PojoSwap<T,?>[] swaps, PojoSwap<?,?>[] childPojoSwaps) {
this.innerClass = innerClass;
this.info = ClassInfo.of(innerClass);
this.beanContext = beanContext;
String notABeanReason = null;
wLock.lock();
try {
// We always immediately add this class meta to the bean context cache so that we can resolve recursive references.
if (beanContext != null && beanContext.cmCache != null && isCacheable(innerClass))
beanContext.cmCache.put(innerClass, this);
ClassMetaBuilder<T> builder = new ClassMetaBuilder(innerClass, beanContext, implClass, swaps, childPojoSwaps);
this.cc = builder.cc;
this.isDelegate = builder.isDelegate;
this.fromStringMethod = builder.fromStringMethod;
this.parentPropertyMethod = builder.parentPropertyMethod;
this.namePropertyMethod = builder.namePropertyMethod;
this.noArgConstructor = builder.noArgConstructor;
this.stringConstructor = builder.stringConstructor;
this.primitiveDefault = builder.primitiveDefault;
this.publicMethods = builder.publicMethods;
this.swaps = builder.swaps.isEmpty() ? null : builder.swaps.toArray(new PojoSwap[builder.swaps.size()]);
this.builderSwap = builder.builderSwap;
this.keyType = builder.keyType;
this.valueType = builder.valueType;
this.elementType = builder.elementType;
notABeanReason = builder.notABeanReason;
this.beanMeta = builder.beanMeta;
this.initException = builder.initException;
this.typePropertyName = builder.typePropertyName;
this.dictionaryName = builder.dictionaryName;
this.invocationHandler = builder.invocationHandler;
this.beanRegistry = builder.beanRegistry;
this.isMemberClass = builder.isMemberClass;
this.isAbstract = builder.isAbstract;
this.implClass = builder.implClass;
this.childUnswapMap = builder.childUnswapMap;
this.childSwapMap = builder.childSwapMap;
this.childPojoSwaps = builder.childPojoSwaps;
this.exampleMethod = builder.exampleMethod;
this.exampleField = builder.exampleField;
this.example = builder.example;
this.args = null;
this.stringMutater = builder.stringMutater;
} catch (ClassMetaRuntimeException e) {
notABeanReason = e.getMessage();
throw e;
} finally {
this.notABeanReason = notABeanReason;
wLock.unlock();
}
}
/**
* Generated classes shouldn't be cacheable to prevent needlessly filling up the cache.
*/
private static boolean isCacheable(Class<?> c) {
String n = c.getName();
char x = n.charAt(n.length()-1); // All generated classes appear to end with digits.
if (x >= '0' && x <= '9') {
if (n.indexOf("$$") != -1 || n.startsWith("sun") || n.startsWith("com.sun") || n.indexOf("$Proxy") != -1)
return false;
}
return true;
}
/**
* Causes thread to wait until constructor has exited.
*/
final void waitForInit() {
rLock.lock();
rLock.unlock();
}
/**
* Copy constructor.
*
* <p>
* Used for creating Map and Collection class metas that shouldn't be cached.
*/
ClassMeta(ClassMeta<T> mainType, ClassMeta<?> keyType, ClassMeta<?> valueType, ClassMeta<?> elementType) {
this.innerClass = mainType.innerClass;
this.info = mainType.info;
this.implClass = mainType.implClass;
this.childPojoSwaps = mainType.childPojoSwaps;
this.childSwapMap = mainType.childSwapMap;
this.childUnswapMap = mainType.childUnswapMap;
this.cc = mainType.cc;
this.fromStringMethod = mainType.fromStringMethod;
this.noArgConstructor = mainType.noArgConstructor;
this.stringConstructor = mainType.stringConstructor;
this.namePropertyMethod = mainType.namePropertyMethod;
this.parentPropertyMethod = mainType.parentPropertyMethod;
this.isDelegate = mainType.isDelegate;
this.isAbstract = mainType.isAbstract;
this.isMemberClass = mainType.isMemberClass;
this.primitiveDefault = mainType.primitiveDefault;
this.publicMethods = mainType.publicMethods;
this.beanContext = mainType.beanContext;
this.elementType = elementType;
this.keyType = keyType;
this.valueType = valueType;
this.invocationHandler = mainType.invocationHandler;
this.beanMeta = mainType.beanMeta;
this.typePropertyName = mainType.typePropertyName;
this.dictionaryName = mainType.dictionaryName;
this.notABeanReason = mainType.notABeanReason;
this.swaps = mainType.swaps;
this.builderSwap = mainType.builderSwap;
this.initException = mainType.initException;
this.beanRegistry = mainType.beanRegistry;
this.exampleMethod = mainType.exampleMethod;
this.exampleField = mainType.exampleField;
this.example = mainType.example;
this.args = null;
this.stringMutater = mainType.stringMutater;
}
/**
* Constructor for args-arrays.
*/
@SuppressWarnings("unchecked")
ClassMeta(ClassMeta<?>[] args) {
this.innerClass = (Class<T>) Object[].class;
this.info = ClassInfo.of(innerClass);
this.args = args;
this.implClass = null;
this.childPojoSwaps = null;
this.childSwapMap = null;
this.childUnswapMap = null;
this.cc = ARGS;
this.fromStringMethod = null;
this.noArgConstructor = null;
this.stringConstructor = null;
this.namePropertyMethod = null;
this.parentPropertyMethod = null;
this.isDelegate = false;
this.isAbstract = false;
this.isMemberClass = false;
this.primitiveDefault = null;
this.publicMethods = null;
this.beanContext = null;
this.elementType = null;
this.keyType = null;
this.valueType = null;
this.invocationHandler = null;
this.beanMeta = null;
this.typePropertyName = null;
this.dictionaryName = null;
this.notABeanReason = null;
this.swaps = null;
this.builderSwap = null;
this.initException = null;
this.beanRegistry = null;
this.exampleMethod = null;
this.exampleField = null;
this.example = null;
this.stringMutater = null;
}
@SuppressWarnings({"unchecked","rawtypes","hiding"})
private final class ClassMetaBuilder<T> {
Class<T> innerClass;
ClassInfo ci;
Class<? extends T> implClass;
BeanContext beanContext;
ClassCategory cc = ClassCategory.OTHER;
boolean
isDelegate = false,
isMemberClass = false,
isAbstract = false;
Method
fromStringMethod = null;
Setter
parentPropertyMethod = null,
namePropertyMethod = null;
ConstructorInfo
noArgConstructor = null,
stringConstructor = null;
Object primitiveDefault = null;
Map<String,Method>
publicMethods = new LinkedHashMap<>();
ClassMeta<?>
keyType = null,
valueType = null,
elementType = null;
String
typePropertyName = null,
notABeanReason = null,
dictionaryName = null;
Throwable initException = null;
BeanMeta beanMeta = null;
AList<PojoSwap> swaps = AList.of();
BuilderSwap builderSwap;
InvocationHandler invocationHandler = null;
BeanRegistry beanRegistry = null;
PojoSwap<?,?>[] childPojoSwaps;
ConcurrentHashMap<Class<?>,PojoSwap<?,?>>
childSwapMap,
childUnswapMap;
Method exampleMethod;
Field exampleField;
String example;
Mutater<String,T> stringMutater;
ClassMetaBuilder(Class<T> innerClass, BeanContext beanContext, Class<? extends T> implClass, PojoSwap<T,?>[] swaps, PojoSwap<?,?>[] childPojoSwaps) {
this.innerClass = innerClass;
this.beanContext = beanContext;
BeanContext bc = beanContext;
this.implClass = implClass;
ClassInfo ici = ClassInfo.of(implClass);
this.childPojoSwaps = childPojoSwaps;
if (childPojoSwaps == null) {
this.childSwapMap = null;
this.childUnswapMap = null;
} else {
this.childSwapMap = new ConcurrentHashMap<>();
this.childUnswapMap = new ConcurrentHashMap<>();
}
Class<T> c = innerClass;
ci = ClassInfo.of(c);
if (ci.isProxy()) {
ci = ci.getProxyFor();
innerClass = this.innerClass = ci.inner();
}
if (c.isPrimitive()) {
if (c == Boolean.TYPE)
cc = BOOLEAN;
else if (c == Byte.TYPE || c == Short.TYPE || c == Integer.TYPE || c == Long.TYPE || c == Float.TYPE || c == Double.TYPE) {
if (c == Float.TYPE || c == Double.TYPE)
cc = DECIMAL;
else
cc = NUMBER;
}
else if (c == Character.TYPE)
cc = CHAR;
else if (c == void.class || c == Void.class)
cc = VOID;
} else {
if (ci.isChildOf(Delegate.class))
isDelegate = true;
if (c == Object.class)
cc = OBJ;
else if (c.isEnum())
cc = ENUM;
else if (c.equals(Class.class))
cc = ClassCategory.CLASS;
else if (ci.isChildOf(Method.class))
cc = METHOD;
else if (ci.isChildOf(CharSequence.class)) {
if (c.equals(String.class))
cc = STR;
else
cc = CHARSEQ;
}
else if (ci.isChildOf(Number.class)) {
if (ci.isChildOfAny(Float.class, Double.class))
cc = DECIMAL;
else
cc = NUMBER;
}
else if (ci.isChildOf(Collection.class))
cc = COLLECTION;
else if (ci.isChildOf(Map.class)) {
if (ci.isChildOf(BeanMap.class))
cc = BEANMAP;
else
cc = MAP;
}
else if (c == Character.class)
cc = CHAR;
else if (c == Boolean.class)
cc = BOOLEAN;
else if (ci.isChildOfAny(Date.class, Calendar.class))
cc = DATE;
else if (c.isArray())
cc = ARRAY;
else if (ci.isChildOfAny(URL.class, URI.class) || bc.hasAnnotation(Uri.class, c))
cc = URI;
else if (ci.isChildOf(Reader.class))
cc = READER;
else if (ci.isChildOf(InputStream.class))
cc = INPUTSTREAM;
else if (ci.is(Optional.class))
cc = OPTIONAL;
}
isMemberClass = ci.isMemberClass() && ci.isNotStatic();
// Find static fromString(String) or equivalent method.
// fromString() must be checked before valueOf() so that Enum classes can create their own
// specialized fromString() methods to override the behavior of Enum.valueOf(String).
// valueOf() is used by enums.
// parse() is used by the java logging Level class.
// forName() is used by Class and Charset
for (String methodName : new String[]{"fromString","fromValue","valueOf","parse","parseString","forName","forString"}) {
if (fromStringMethod == null) {
for (MethodInfo m : ci.getPublicMethods()) {
if (m.isAll(STATIC, PUBLIC, NOT_DEPRECATED) && m.hasName(methodName) && m.hasReturnType(c) && m.hasParamTypes(String.class)) {
fromStringMethod = m.inner();
break;
}
}
}
}
// Find example() method if present.
for (MethodInfo m : ci.getPublicMethods()) {
if (m.isAll(PUBLIC, NOT_DEPRECATED, STATIC) && m.hasName("example") && m.hasFuzzyParamTypes(BeanSession.class)) {
exampleMethod = m.inner();
break;
}
}
for (FieldInfo f : ci.getAllFieldsParentFirst()) {
if (bc.hasAnnotation(ParentProperty.class, f)) {
if (f.isStatic())
throw new ClassMetaRuntimeException(c, "@ParentProperty used on invalid field ''{0}''. Must be static.", f);
f.setAccessible();
parentPropertyMethod = new Setter.FieldSetter(f.inner());
}
if (bc.hasAnnotation(NameProperty.class, f)) {
if (f.isStatic())
throw new ClassMetaRuntimeException(c, "@NameProperty used on invalid field ''{0}''. Must be static.", f);
f.setAccessible();
namePropertyMethod = new Setter.FieldSetter(f.inner());
}
}
for (FieldInfo f : ci.getDeclaredFields()) {
if (bc.hasAnnotation(Example.class, f)) {
if (! (f.isStatic() && ci.isParentOf(f.getType().inner())))
throw new ClassMetaRuntimeException(c, "@Example used on invalid field ''{0}''. Must be static and an instance of the type.", f);
f.setAccessible();
exampleField = f.inner();
}
}
// Find @NameProperty and @ParentProperty methods if present.
for (MethodInfo m : ci.getAllMethodsParentFirst()) {
if (bc.hasAnnotation(ParentProperty.class, m)) {
if (m.isStatic() || ! m.hasNumParams(1))
throw new ClassMetaRuntimeException(c, "@ParentProperty used on invalid method ''{0}''. Must not be static and have one argument.", m);
m.setAccessible();
parentPropertyMethod = new Setter.MethodSetter(m.inner());
}
if (bc.hasAnnotation(NameProperty.class, m)) {
if (m.isStatic() || ! m.hasNumParams(1))
throw new ClassMetaRuntimeException(c, "@NameProperty used on invalid method ''{0}''. Must not be static and have one argument.", m);
m.setAccessible();
namePropertyMethod = new Setter.MethodSetter(m.inner());
}
}
for (MethodInfo m : ci.getDeclaredMethods()) {
if (bc.hasAnnotation(Example.class, m)) {
if (! (m.isStatic() && m.hasFuzzyParamTypes(BeanSession.class) && ci.isParentOf(m.getReturnType().inner())))
throw new ClassMetaRuntimeException(c, "@Example used on invalid method ''{0}''. Must be static and return an instance of the declaring class.", m);
m.setAccessible();
exampleMethod = m.inner();
}
}
// Note: Primitive types are normally abstract.
isAbstract = ci.isAbstract() && ci.isNotPrimitive();
// Find constructor(String) method if present.
for (ConstructorInfo cs : ci.getPublicConstructors()) {
if (cs.isPublic() && cs.isNotDeprecated()) {
List<ClassInfo> pt = cs.getParamTypes();
if (pt.size() == (isMemberClass ? 1 : 0) && c != Object.class && ! isAbstract) {
noArgConstructor = cs;
} else if (pt.size() == (isMemberClass ? 2 : 1)) {
ClassInfo arg = pt.get(isMemberClass ? 1 : 0);
if (arg.is(String.class))
stringConstructor = cs;
}
}
}
primitiveDefault = ci.getPrimitiveDefault();
for (MethodInfo m : ci.getPublicMethods())
if (m.isAll(PUBLIC, NOT_DEPRECATED))
publicMethods.put(m.getSignature(), m.inner());
if (innerClass != Object.class) {
ClassInfo x = implClass == null ? ci : ici;
noArgConstructor = x.getPublicConstructor();
}
BeanFilter beanFilter = findBeanFilter(bc);
MarshalledFilter marshalledFilter = findMarshalledFilter(bc);
if (swaps != null)
this.swaps.a(swaps);
if (bc != null)
this.builderSwap = BuilderSwap.findSwapFromPojoClass(bc, c, bc.getBeanConstructorVisibility(), bc.getBeanMethodVisibility());
findSwaps(this.swaps, bc);
try {
// If this is an array, get the element type.
if (cc == ARRAY)
elementType = findClassMeta(innerClass.getComponentType());
// If this is a MAP, see if it's parameterized (e.g. AddressBook extends HashMap<String,Person>)
else if (cc == MAP) {
ClassMeta[] parameters = findParameters();
if (parameters != null && parameters.length == 2) {
keyType = parameters[0];
valueType = parameters[1];
} else {
keyType = findClassMeta(Object.class);
valueType = findClassMeta(Object.class);
}
}
// If this is a COLLECTION, see if it's parameterized (e.g. AddressBook extends LinkedList<Person>)
else if (cc == COLLECTION || cc == OPTIONAL) {
ClassMeta[] parameters = findParameters();
if (parameters != null && parameters.length == 1) {
elementType = parameters[0];
} else {
elementType = findClassMeta(Object.class);
}
}
// If the category is unknown, see if it's a bean.
// Note that this needs to be done after all other initialization has been done.
else if (cc == OTHER) {
BeanMeta newMeta = null;
try {
newMeta = new BeanMeta(ClassMeta.this, bc, beanFilter, null);
notABeanReason = newMeta.notABeanReason;
// Always get these even if it's not a bean:
beanRegistry = newMeta.beanRegistry;
typePropertyName = newMeta.typePropertyName;
} catch (RuntimeException e) {
notABeanReason = e.getMessage();
throw e;
}
if (notABeanReason == null)
beanMeta = newMeta;
}
} catch (NoClassDefFoundError e) {
initException = e;
} catch (RuntimeException e) {
initException = e;
throw e;
}
if (beanMeta != null)
dictionaryName = beanMeta.getDictionaryName();
if (beanMeta != null && bc != null && bc.isUseInterfaceProxies() && innerClass.isInterface())
invocationHandler = new BeanProxyInvocationHandler<T>(beanMeta);
if (bc != null) {
for (Bean b : bc.getAnnotations(Bean.class, c)) {
if (b.dictionary().length != 0)
beanRegistry = new BeanRegistry(bc, null, b.dictionary());
// This could be a non-bean POJO with a type name.
if (dictionaryName == null && ! b.typeName().isEmpty())
dictionaryName = b.typeName();
}
}
if (beanFilter != null)
example = beanFilter.getExample();
if (example == null && marshalledFilter != null)
example = marshalledFilter.getExample();
if (example == null && bc != null)
for (Example e : bc.getAnnotations(Example.class, c))
if (! e.value().isEmpty())
example = e.value();
if (example == null) {
switch(cc) {
case BOOLEAN:
example = "true";
break;
case CHAR:
example = "a";
break;
case CHARSEQ:
case STR:
example = "foo";
break;
case DECIMAL:
if (isFloat())
example = "1.0";
else if (isDouble())
example = "1.0";
break;
case ENUM:
Iterator<? extends Enum> i = EnumSet.allOf((Class<? extends Enum>)c).iterator();
if (i.hasNext())
example = beanContext.isUseEnumNames() ? i.next().name() : i.next().toString();
break;
case NUMBER:
if (isShort())
example = "1";
else if (isInteger())
example = "1";
else if (isLong())
example = "1";
break;
case URI:
case ARGS:
case ARRAY:
case BEANMAP:
case CLASS:
case COLLECTION:
case DATE:
case INPUTSTREAM:
case MAP:
case METHOD:
case OBJ:
case OTHER:
case READER:
case OPTIONAL:
case VOID:
break;
}
}
this.stringMutater = Mutaters.get(String.class, c);
}
private BeanFilter findBeanFilter(BeanContext bc) {
try {
List<Bean> ba = info.getAnnotations(Bean.class, bc);
if (! ba.isEmpty())
return BeanFilter.create(innerClass).applyAnnotations(ba).build();
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
private MarshalledFilter findMarshalledFilter(BeanContext bc) {
try {
List<Marshalled> ba = info.getAnnotations(Marshalled.class, bc);
if (! ba.isEmpty())
return MarshalledFilter.create(innerClass).applyAnnotations(ba).build();
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
private void findSwaps(List<PojoSwap> l, BeanContext bc) {
if (bc != null) {
for (Swap swap : bc.getAnnotations(Swap.class, innerClass))
l.add(createPojoSwap(swap));
for (Swaps swaps : bc.getAnnotations(Swaps.class, innerClass))
for (Swap swap : swaps.value())
l.add(createPojoSwap(swap));
}
PojoSwap defaultSwap = DefaultSwaps.find(ci);
if (defaultSwap == null)
defaultSwap = AutoObjectSwap.find(bc, ci);
if (defaultSwap == null)
defaultSwap = AutoNumberSwap.find(bc, ci);
if (defaultSwap == null)
defaultSwap = AutoMapSwap.find(bc, ci);
if (defaultSwap == null)
defaultSwap = AutoListSwap.find(bc, ci);
if (defaultSwap != null)
l.add(defaultSwap);
}
private PojoSwap<T,?> createPojoSwap(Swap s) {
Class<?> c = s.value();
if (c == Null.class)
c = s.impl();
ClassInfo ci = ClassInfo.of(c);
if (ci.isChildOf(PojoSwap.class)) {
PojoSwap ps = castOrCreate(PojoSwap.class, c);
if (s.mediaTypes().length > 0)
ps.forMediaTypes(MediaType.ofAll(s.mediaTypes()));
if (! s.template().isEmpty())
ps.withTemplate(s.template());
return ps;
}
if (ci.isChildOf(Surrogate.class)) {
List<SurrogateSwap<?,?>> l = SurrogateSwap.findPojoSwaps(c, beanContext);
if (! l.isEmpty())
return (PojoSwap<T,?>)l.iterator().next();
}
throw new ClassMetaRuntimeException(c, "Invalid swap class ''{0}'' specified. Must extend from PojoSwap or Surrogate.", c);
}
private ClassMeta<?> findClassMeta(Class<?> c) {
return beanContext.getClassMeta(c, false);
}
private ClassMeta<?>[] findParameters() {
return beanContext.findParameters(innerClass, innerClass);
}
}
/**
* Returns the {@link ClassInfo} wrapper for the underlying class.
*
* @return The {@link ClassInfo} wrapper for the underlying class, never <jk>null</jk>.
*/
public ClassInfo getInfo() {
return info;
}
/**
* Returns the type property name associated with this class and subclasses.
*
* <p>
* If <jk>null</jk>, <js>"_type"</js> should be assumed.
*
* @return
* The type property name associated with this bean class, or <jk>null</jk> if there is no explicit type
* property name defined or this isn't a bean.
*/
public String getBeanTypePropertyName() {
return typePropertyName;
}
/**
* Returns the bean dictionary name associated with this class.
*
* <p>
* The lexical name is defined by {@link Bean#typeName() @Bean(typeName)}.
*
* @return
* The type name associated with this bean class, or <jk>null</jk> if there is no type name defined or this
* isn't a bean.
*/
public String getDictionaryName() {
return dictionaryName;
}
/**
* Returns the bean registry for this class.
*
* <p>
* This bean registry contains names specified in the {@link Bean#dictionary() @Bean(dictionary)} annotation
* defined on the class, regardless of whether the class is an actual bean.
* This allows interfaces to define subclasses with type names.
*
* @return The bean registry for this class, or <jk>null</jk> if no bean registry is associated with it.
*/
public BeanRegistry getBeanRegistry() {
return beanRegistry;
}
/**
* Returns the category of this class.
*
* @return The category of this class.
*/
public ClassCategory getClassCategory() {
return cc;
}
/**
* Returns <jk>true</jk> if this class is a superclass of or the same as the specified class.
*
* @param c The comparison class.
* @return <jk>true</jk> if this class is a superclass of or the same as the specified class.
*/
public boolean isAssignableFrom(Class<?> c) {
return info.isChildOf(c);
}
/**
* Returns <jk>true</jk> if this class is a subclass of or the same as the specified class.
*
* @param c The comparison class.
* @return <jk>true</jk> if this class is a subclass of or the same as the specified class.
*/
public boolean isInstanceOf(Class<?> c) {
return info.isParentOf(c);
}
/**
* Returns <jk>true</jk> if this class or any child classes has a {@link PojoSwap} associated with it.
*
* <p>
* Used when transforming bean properties to prevent having to look up transforms if we know for certain that no
* transforms are associated with a bean property.
*
* @return <jk>true</jk> if this class or any child classes has a {@link PojoSwap} associated with it.
*/
protected boolean hasChildPojoSwaps() {
return childPojoSwaps != null;
}
/**
* Returns the {@link PojoSwap} where the specified class is the same/subclass of the normal class of one of the
* child POJO swaps associated with this class.
*
* @param normalClass The normal class being resolved.
* @return The resolved {@link PojoSwap} or <jk>null</jk> if none were found.
*/
protected PojoSwap<?,?> getChildPojoSwapForSwap(Class<?> normalClass) {
if (childSwapMap != null) {
PojoSwap<?,?> s = childSwapMap.get(normalClass);
if (s == null) {
for (PojoSwap<?,?> f : childPojoSwaps)
if (s == null && f.getNormalClass().isParentOf(normalClass))
s = f;
if (s == null)
s = PojoSwap.NULL;
PojoSwap<?,?> s2 = childSwapMap.putIfAbsent(normalClass, s);
if (s2 != null)
s = s2;
}
if (s == PojoSwap.NULL)
return null;
return s;
}
return null;
}
/**
* Returns the {@link PojoSwap} where the specified class is the same/subclass of the swap class of one of the child
* POJO swaps associated with this class.
*
* @param swapClass The swap class being resolved.
* @return The resolved {@link PojoSwap} or <jk>null</jk> if none were found.
*/
protected PojoSwap<?,?> getChildPojoSwapForUnswap(Class<?> swapClass) {
if (childUnswapMap != null) {
PojoSwap<?,?> s = childUnswapMap.get(swapClass);
if (s == null) {
for (PojoSwap<?,?> f : childPojoSwaps)
if (s == null && f.getSwapClass().isParentOf(swapClass))
s = f;
if (s == null)
s = PojoSwap.NULL;
PojoSwap<?,?> s2 = childUnswapMap.putIfAbsent(swapClass, s);
if (s2 != null)
s = s2;
}
if (s == PojoSwap.NULL)
return null;
return s;
}
return null;
}
/**
* Locates the no-arg constructor for the specified class.
*
* <p>
* Constructor must match the visibility requirements specified by parameter 'v'.
* If class is abstract, always returns <jk>null</jk>.
* Note that this also returns the 1-arg constructor for non-static member classes.
*
* @param c The class from which to locate the no-arg constructor.
* @param v The minimum visibility.
* @return The constructor, or <jk>null</jk> if no no-arg constructor exists with the required visibility.
*/
@SuppressWarnings({"unchecked"})
protected static <T> Constructor<? extends T> findNoArgConstructor(Class<?> c, Visibility v) {
ClassInfo ci = ClassInfo.of(c);
if (ci.isAbstract())
return null;
boolean isMemberClass = ci.isMemberClass() && ci.isNotStatic();
for (ConstructorInfo cc : ci.getPublicConstructors()) {
if (cc.hasNumParams(isMemberClass ? 1 : 0) && cc.isVisible(v) && cc.isNotDeprecated())
return (Constructor<? extends T>) v.transform(cc.inner());
}
return null;
}
/**
* Returns the {@link Class} object that this class type wraps.
*
* @return The wrapped class object.
*/
public Class<T> getInnerClass() {
return innerClass;
}
/**
* Returns the serialized (swapped) form of this class if there is an {@link PojoSwap} associated with it.
*
* @param session
* The bean session.
* <br>Required because the swap used may depend on the media type being serialized or parsed.
* @return The serialized class type, or this object if no swap is associated with the class.
*/
@BeanIgnore
public ClassMeta<?> getSerializedClassMeta(BeanSession session) {
PojoSwap<T,?> ps = getSwap(session);
return (ps == null ? this : ps.getSwapClassMeta(session));
}
/**
* Returns the example of this class.
*
* @param session
* The bean session.
* <br>Required because the example method may take it in as a parameter.
* @return The serialized class type, or this object if no swap is associated with the class.
*/
@SuppressWarnings({"unchecked","rawtypes"})
@BeanIgnore
public T getExample(BeanSession session) {
try {
if (example != null)
return session.getContext().getContext(JsonParser.class).parse(example, this);
if (exampleMethod != null)
return (T)MethodInfo.of(exampleMethod).invokeFuzzy(null, session);
if (exampleField != null)
return (T)exampleField.get(null);
if (isCollection()) {
Object etExample = getElementType().getExample(session);
if (etExample != null) {
if (canCreateNewInstance()) {
Collection c = (Collection)newInstance();
c.add(etExample);
return (T)c;
}
return (T)Collections.singleton(etExample);
}
} else if (isArray()) {
Object etExample = getElementType().getExample(session);
if (etExample != null) {
Object o = Array.newInstance(getElementType().innerClass, 1);
Array.set(o, 0, etExample);
return (T)o;
}
} else if (isMap()) {
Object vtExample = getValueType().getExample(session);
Object ktExample = getKeyType().getExample(session);
if (ktExample != null && vtExample != null) {
if (canCreateNewInstance()) {
Map m = (Map)newInstance();
m.put(ktExample, vtExample);
return (T)m;
}