/
Classes.java
681 lines (627 loc) · 21.1 KB
/
Classes.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
/*
* Copyright (c) 2008, Rickard Öberg. All Rights Reserved.
*
* Licensed 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.qi4j.api.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.qi4j.api.composite.ModelDescriptor;
import org.qi4j.functional.Function;
import org.qi4j.functional.Iterables;
import org.qi4j.functional.Specification;
import static org.qi4j.functional.Iterables.cast;
import static org.qi4j.functional.Iterables.empty;
import static org.qi4j.functional.Iterables.flatten;
import static org.qi4j.functional.Iterables.flattenIterables;
import static org.qi4j.functional.Iterables.iterable;
import static org.qi4j.functional.Iterables.map;
import static org.qi4j.functional.Iterables.matchesAny;
import static org.qi4j.functional.Iterables.prepend;
/**
* Useful methods for handling Classes.
*/
public final class Classes
{
private final static Map<Type, Type> wrapperClasses = new HashMap<Type, Type>();
static
{
wrapperClasses.put( boolean.class, Boolean.class );
wrapperClasses.put( byte.class, Byte.class );
wrapperClasses.put( short.class, Short.class );
wrapperClasses.put( char.class, Character.class );
wrapperClasses.put( int.class, Integer.class );
wrapperClasses.put( long.class, Long.class );
wrapperClasses.put( float.class, Float.class );
wrapperClasses.put( double.class, Double.class );
}
private final static Map<Type, Type> primitiveClasses = new HashMap<Type, Type>();
static
{
primitiveClasses.put( boolean.class, Boolean.class );
primitiveClasses.put( byte.class, Byte.class );
primitiveClasses.put( short.class, Short.class );
primitiveClasses.put( char.class, Character.class );
primitiveClasses.put( int.class, Integer.class );
primitiveClasses.put( long.class, Long.class );
primitiveClasses.put( float.class, Float.class );
primitiveClasses.put( double.class, Double.class );
}
/**
* Convert from primitive class (int, short, double, etc.) to wrapper class (Integer, Short, Double, etc.).
* Return the same class if it's not a primitive class. This can therefore safely be used on all types
* to ensure that they are not primitives.
*/
private static final Function<Type, Type> WRAPPER_CLASS = new Function<Type, Type>()
{
@Override
public Type map( Type aClass )
{
Type wrapperClass = wrapperClasses.get( aClass );
return wrapperClass == null ? aClass : wrapperClass;
}
};
/**
* Convert from wrapper class (Integer, Short, Double, etc.) to primitive class (int, short, double, etc.).
* Return the same class if it's not a wrapper class. This can therefore safely be used on all types
* to ensure that they are primitives if possible.
*/
private static final Function<Type, Type> PRIMITIVE_CLASS = new Function<Type, Type>()
{
@Override
public Type map( Type aClass )
{
Type primitiveClass = primitiveClasses.get( aClass );
return primitiveClass == null ? aClass : primitiveClass;
}
};
/**
* Function that extract the raw class of a type.
*/
public static final Function<Type, Class<?>> RAW_CLASS = new Function<Type, Class<?>>()
{
@Override
public Class<?> map( Type genericType )
{
// Calculate raw type
if( genericType instanceof Class )
{
return (Class<?>) genericType;
}
else if( genericType instanceof ParameterizedType )
{
return (Class<?>) ( (ParameterizedType) genericType ).getRawType();
}
else if( genericType instanceof TypeVariable )
{
return (Class<?>) ( (TypeVariable) genericType ).getGenericDeclaration();
}
else if( genericType instanceof WildcardType )
{
return (Class<?>) ( (WildcardType) genericType ).getUpperBounds()[ 0 ];
}
else if( genericType instanceof GenericArrayType )
{
Object temp = Array.newInstance( (Class<?>) ( (GenericArrayType) genericType ).getGenericComponentType(), 0 );
return temp.getClass();
}
throw new IllegalArgumentException( "Could not extract the raw class of " + genericType );
}
};
private static final Function<AccessibleObject, Type> TYPE_OF = new Function<AccessibleObject, Type>()
{
@Override
public Type map( AccessibleObject accessor )
{
return accessor instanceof Method ? ( (Method) accessor ).getGenericReturnType() : ( (Field) accessor ).getGenericType();
}
};
private static final Function<Type, Iterable<Class<?>>> CLASS_HIERARCHY = new Function<Type, Iterable<Class<?>>>()
{
@Override
public Iterable<Class<?>> map( Type type )
{
if( type == null )
{
return empty();
}
if( type.equals( Object.class ) )
{
Class<?> aClass = (Class<?>) type;
return cast( iterable( aClass ) );
}
else
{
type = RAW_CLASS.map( type );
Class superclass = ( (Class) type ).getSuperclass();
return prepend( (Class<?>) type, map( superclass ) );
}
}
};
private static final Function<Type, Iterable<Type>> INTERFACES_OF = new Function<Type, Iterable<Type>>()
{
@Override
public Iterable<Type> map( Type type )
{
Class clazz = RAW_CLASS.map( type );
if( clazz.isInterface() )
{
Iterable<Type> genericInterfaces = iterable( clazz.getGenericInterfaces() );
Iterable<Type> flattenIterables = flattenIterables( Iterables.map( INTERFACES_OF, genericInterfaces ) );
return prepend( type, flattenIterables );
}
else
{
if( type.equals( Object.class ) )
{
return iterable( clazz.getGenericInterfaces() );
}
else
{
return flatten( flattenIterables( Iterables.map( INTERFACES_OF,
iterable( clazz.getGenericInterfaces() ) ) ),
INTERFACES_OF.map( RAW_CLASS.map( type ).getSuperclass() ) );
}
}
}
};
private static final Function<Type, Iterable<Type>> TYPES_OF = new Function<Type, Iterable<Type>>()
{
@Override
public Iterable<Type> map( Type type )
{
Class clazz = RAW_CLASS.map( type );
if( clazz.isInterface() )
{
Iterable<Type> genericInterfaces = iterable( clazz.getGenericInterfaces() );
Iterable<Type> flattenIterables = flattenIterables( Iterables.map( INTERFACES_OF, genericInterfaces ) );
return prepend( clazz, flattenIterables );
}
else
{
return flatten( CLASS_HIERARCHY.map( type ),
flattenIterables( Iterables.map( INTERFACES_OF, CLASS_HIERARCHY.map( type ) ) ) );
}
}
};
public static Type typeOf( AccessibleObject from )
{
return TYPE_OF.map( from );
}
public static Iterable<Type> typesOf( Iterable<Type> types )
{
Iterable<Type> result = empty();
for( Type type : types )
{
result = flatten( result, typesOf( type ) );
}
return result;
}
public static Iterable<Type> typesOf( Type type )
{
return TYPES_OF.map( type );
}
public static Iterable<? extends Type> interfacesOf( Iterable<? extends Type> types )
{
Iterable<Type> result = empty();
for( Type type : types )
{
result = flatten( result, interfacesOf( type ) );
}
return result;
}
public static Iterable<Type> interfacesOf( Type type )
{
return INTERFACES_OF.map( type );
}
public static Iterable<Class<?>> classHierarchy( Class<?> type )
{
return CLASS_HIERARCHY.map( type );
}
public static Type wrapperClass( Type type )
{
return WRAPPER_CLASS.map( type );
}
public static Specification<Class<?>> isAssignableFrom( final Class clazz )
{
return new Specification<Class<?>>()
{
@Override
public boolean satisfiedBy( Class<?> item )
{
return clazz.isAssignableFrom( item );
}
};
}
public static Specification<Object> instanceOf( final Class clazz )
{
return new Specification<Object>()
{
@Override
public boolean satisfiedBy( Object item )
{
return clazz.isInstance( item );
}
};
}
public static Specification<Class<?>> hasModifier( final int classModifier )
{
return new Specification<Class<?>>()
{
@Override
public boolean satisfiedBy( Class<?> item )
{
return ( item.getModifiers() & classModifier ) != 0;
}
};
}
public static <T> Function<Type, Iterable<T>> forClassHierarchy( final Function<Class<?>, Iterable<T>> function )
{
return new Function<Type, Iterable<T>>()
{
@Override
public Iterable<T> map( Type type )
{
return flattenIterables( Iterables.map( function, CLASS_HIERARCHY.map( type ) ) );
}
};
}
public static <T> Function<Type, Iterable<T>> forTypes( final Function<Type, Iterable<T>> function )
{
return new Function<Type, Iterable<T>>()
{
@Override
public Iterable<T> map( Type type )
{
return flattenIterables( Iterables.map( function, TYPES_OF.map( type ) ) );
}
};
}
public static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces )
{
Set<Class<?>> newSet = new LinkedHashSet<Class<?>>();
for( Class type : interfaces )
{
if( type.isInterface() && type.getDeclaredMethods().length > 0 )
{
newSet.add( type );
}
}
return newSet;
}
public static String simpleGenericNameOf( Type type )
{
StringBuilder sb = new StringBuilder();
simpleGenericNameOf( sb, type );
return sb.toString();
}
private static void simpleGenericNameOf( StringBuilder sb, Type type )
{
if( type instanceof Class )
{
sb.append( ( (Class) type ).getSimpleName() );
}
else if( type instanceof ParameterizedType )
{
ParameterizedType pt = (ParameterizedType) type;
simpleGenericNameOf( sb, pt.getRawType() );
sb.append( "<" );
boolean atLeastOne = false;
for( Type typeArgument : pt.getActualTypeArguments() )
{
if( atLeastOne )
{
sb.append( ", " );
}
simpleGenericNameOf( sb, typeArgument );
atLeastOne = true;
}
sb.append( ">" );
}
else if( type instanceof GenericArrayType )
{
GenericArrayType gat = (GenericArrayType) type;
simpleGenericNameOf( sb, gat.getGenericComponentType() );
sb.append( "[]" );
}
else if( type instanceof TypeVariable )
{
TypeVariable tv = (TypeVariable) type;
sb.append( tv.getName() );
}
else if( type instanceof WildcardType )
{
WildcardType wt = (WildcardType) type;
sb.append( "? extends " );
boolean atLeastOne = false;
for( Type typeArgument : wt.getUpperBounds() )
{
if( atLeastOne )
{
sb.append( ", " );
}
simpleGenericNameOf( sb, typeArgument );
atLeastOne = true;
}
}
else
{
throw new IllegalArgumentException( "Don't know how to deal with type:" + type );
}
}
public static <AnnotationType extends Annotation>
AnnotationType findAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type, Class<AnnotationType> annotationClass )
{
AnnotationType result = null;
for( Type clazz : Classes.TYPES_OF.map( type ) )
{
result = Classes.RAW_CLASS.map( clazz ).getAnnotation( annotationClass );
if( result != null )
{
break;
}
}
return result;
}
public static Specification<Member> memberNamed( final String name )
{
return new Specification<Member>()
{
@Override
public boolean satisfiedBy( Member item )
{
return item.getName().equals( name );
}
};
}
/**
* Given a type variable, find what it resolves to given the declaring class where type
* variable was found and a top class that extends the declaring class.
*
* @param name
* @param declaringClass
* @param topClass
*
* @return
*/
public static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass )
{
Type type = resolveTypeVariable( name, declaringClass, new HashMap<TypeVariable, Type>(), topClass );
if( type == null )
{
type = Object.class;
}
return type;
}
private static Type resolveTypeVariable( TypeVariable name,
Class declaringClass,
Map<TypeVariable, Type> mappings,
Class current
)
{
if( current.equals( declaringClass ) )
{
Type resolvedType = name;
while( resolvedType instanceof TypeVariable )
{
resolvedType = mappings.get( resolvedType );
}
return resolvedType;
}
List<Type> types = new ArrayList<Type>();
for( Type type : current.getGenericInterfaces() )
{
Iterable<Type> interfaces = Classes.INTERFACES_OF.map( type );
for( Type anInterface : interfaces )
{
if( !types.contains( anInterface ) )
{
types.add( anInterface );
}
}
types.add( type );
}
if( current.getGenericSuperclass() != null )
{
types.add( current.getGenericSuperclass() );
}
for( Type type : types )
{
Class subClass;
if( type instanceof ParameterizedType )
{
ParameterizedType pt = (ParameterizedType) type;
Type[] args = pt.getActualTypeArguments();
Class clazz = (Class) pt.getRawType();
TypeVariable[] vars = clazz.getTypeParameters();
for( int i = 0; i < vars.length; i++ )
{
TypeVariable var = vars[ i ];
Type mappedType = args[ i ];
mappings.put( var, mappedType );
}
subClass = (Class) pt.getRawType();
}
else
{
subClass = (Class) type;
}
Type resolvedType = resolveTypeVariable( name, declaringClass, mappings, subClass );
if( resolvedType != null )
{
return resolvedType;
}
}
return null;
}
/**
* Get URI for a class.
*
* @param clazz class
*
* @return URI
*
* @throws NullPointerException if clazz is null
*/
public static String toURI( final Class clazz )
throws NullPointerException
{
return toURI( clazz.getName() );
}
/**
* Get URI for a class name.
* <p/>
* Example:
* Class name com.example.Foo$Bar
* is converted to
* URI urn:qi4j:com.example.Foo-Bar
*
* @param className class name
*
* @return URI
*
* @throws NullPointerException if className is null
*/
public static String toURI( String className )
throws NullPointerException
{
className = normalizeClassToURI( className );
return "urn:qi4j:type:" + className;
}
/**
* Get class name from a URI
*
* @param uri URI
*
* @return class name
*
* @throws NullPointerException if uri is null
*/
public static String toClassName( String uri )
throws NullPointerException
{
uri = uri.substring( "urn:qi4j:type:".length() );
uri = denormalizeURIToClass( uri );
return uri;
}
public static String normalizeClassToURI( String className )
{
return className.replace( '$', '-' );
}
public static String denormalizeURIToClass( String uriPart )
{
return uriPart.replace( '-', '$' );
}
public static Specification<ModelDescriptor> modelTypeSpecification( final String className )
{
return new Specification<ModelDescriptor>()
{
@Override
public boolean satisfiedBy( ModelDescriptor item )
{
return matchesAny( new Specification<String>()
{
@Override
public boolean satisfiedBy( String item )
{
return item.equals( className );
}
}, map( new Function<Class<?>, String>()
{
@Override
public String map( Class<?> item )
{
return item.getName();
}
}, item.types() ) );
}
};
}
public static Specification<ModelDescriptor> exactTypeSpecification( final Class type )
{
return new Specification<ModelDescriptor>()
{
@Override
public boolean satisfiedBy( ModelDescriptor item )
{
return matchesAny( new Specification<Class<?>>()
{
@Override
public boolean satisfiedBy( Class<?> item )
{
return item.equals( type );
}
}, item.types() );
}
};
}
public static Specification<ModelDescriptor> assignableTypeSpecification( final Class type )
{
return new Specification<ModelDescriptor>()
{
@Override
public boolean satisfiedBy( ModelDescriptor item )
{
return matchesAny( new Specification<Class<?>>()
{
@Override
public boolean satisfiedBy( Class<?> itemType )
{
return !type.equals( itemType ) && type.isAssignableFrom( itemType );
}
}, item.types() );
}
};
}
public static String toString( Iterable<? extends Class> type )
{
StringBuilder builder = new StringBuilder();
builder.append( "[" );
boolean first = true;
for( Class c : type )
{
if( !first )
{
builder.append( "," );
}
first = false;
builder.append( c.getSimpleName() );
}
builder.append( "]" );
return builder.toString();
}
public static Function<Type, String> toClassName()
{
return new Function<Type, String>()
{
@Override
public String map( Type type )
{
return RAW_CLASS.map( type ).getName();
}
};
}
}