forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReflectHelper.cs
1039 lines (930 loc) · 34.8 KB
/
ReflectHelper.cs
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using NHibernate.Properties;
using NHibernate.Type;
using NHibernate.Engine;
namespace NHibernate.Util
{
/// <summary>
/// Helper class for Reflection related code.
/// </summary>
public static class ReflectHelper
{
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ReflectHelper));
public const BindingFlags AnyVisibilityInstance = BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic;
private static readonly System.Type[] NoClasses = System.Type.EmptyTypes;
private static readonly MethodInfo Exception_InternalPreserveStackTrace =
typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
internal static T CastOrThrow<T>(object obj, string supportMessage) where T : class
{
if (obj is T t)
return t;
var typeKind = typeof(T).IsInterface ? "interface" : "class";
var objType = obj?.GetType().FullName ?? "Object must not be null and";
throw new ArgumentException($@"{objType} requires to implement {typeof(T).FullName} {typeKind} to support {supportMessage}.");
}
/// <summary>
/// Extract the <see cref="MethodInfo"/> from a given expression.
/// </summary>
/// <typeparam name="TSource">The declaring-type of the method.</typeparam>
/// <param name="method">The method.</param>
/// <returns>The <see cref="MethodInfo"/> of the no-generic method or the generic-definition for a generic-method.</returns>
/// <seealso cref="MethodInfo.GetGenericMethodDefinition"/>
public static MethodInfo GetMethodDefinition<TSource>(Expression<Action<TSource>> method)
{
MethodInfo methodInfo = GetMethod(method);
return methodInfo.IsGenericMethod ? methodInfo.GetGenericMethodDefinition() : methodInfo;
}
/// <summary>
/// Extract the <see cref="MethodInfo"/> from a given expression.
/// </summary>
/// <typeparam name="TSource">The declaring-type of the method.</typeparam>
/// <param name="method">The method.</param>
/// <returns>The <see cref="MethodInfo"/> of the method.</returns>
public static MethodInfo GetMethod<TSource>(Expression<Action<TSource>> method)
{
if (method == null)
throw new ArgumentNullException(nameof(method));
return ((MethodCallExpression)method.Body).Method;
}
/// <summary>
/// Extract the <see cref="MethodInfo"/> from a given expression.
/// </summary>
/// <typeparam name="TSource">The declaring-type of the method.</typeparam>
/// <typeparam name="TResult">The return type of the method.</typeparam>
/// <param name="method">The method.</param>
/// <returns>The <see cref="MethodInfo"/> of the method.</returns>
public static MethodInfo GetMethod<TSource, TResult>(Expression<Func<TSource, TResult>> method)
{
if (method == null)
throw new ArgumentNullException(nameof(method));
return ((MethodCallExpression) method.Body).Method;
}
/// <summary>
/// Extract the <see cref="MethodInfo"/> from a given expression.
/// </summary>
/// <param name="method">The method.</param>
/// <returns>The <see cref="MethodInfo"/> of the no-generic method or the generic-definition for a generic-method.</returns>
/// <seealso cref="MethodInfo.GetGenericMethodDefinition"/>
public static MethodInfo GetMethodDefinition(Expression<System.Action> method)
{
MethodInfo methodInfo = GetMethod(method);
return methodInfo.IsGenericMethod ? methodInfo.GetGenericMethodDefinition() : methodInfo;
}
/// <summary>
/// Extract the <see cref="MethodInfo"/> from a given expression.
/// </summary>
/// <param name="method">The method.</param>
/// <returns>The <see cref="MethodInfo"/> of the method.</returns>
public static MethodInfo GetMethod(Expression<System.Action> method)
{
if (method == null)
throw new ArgumentNullException(nameof(method));
return ((MethodCallExpression)method.Body).Method;
}
/// <summary> Get a <see cref="MethodInfo"/> from a method group </summary>
/// <param name="func">A method group</param>
internal static MethodInfo FastGetMethod<TResult>(System.Func<TResult> func)
{
return func.Method;
}
/// <summary> Get a <see cref="MethodInfo"/> from a method group </summary>
/// <param name="func">A method group</param>
/// <param name="a">A dummy parameter</param>
internal static MethodInfo FastGetMethod<T, TResult>(System.Func<T, TResult> func, T a)
{
return func.Method;
}
/// <summary> Get a <see cref="MethodInfo"/> from a method group </summary>
/// <param name="func">A method group</param>
/// <param name="a1">A dummy parameter</param>
/// <param name="a2">A dummy parameter</param>
internal static MethodInfo FastGetMethod<T1, T2, TResult>(System.Func<T1, T2, TResult> func, T1 a1, T2 a2)
{
return func.Method;
}
/// <summary> Get a <see cref="MethodInfo"/> from a method group </summary>
/// <param name="func">A method group</param>
/// <param name="a1">A dummy parameter</param>
/// <param name="a2">A dummy parameter</param>
/// <param name="a3">A dummy parameter</param>
internal static MethodInfo FastGetMethod<T1, T2, T3, TResult>(System.Func<T1, T2, T3, TResult> func, T1 a1, T2 a2, T3 a3)
{
return func.Method;
}
/// <summary> Get a <see cref="MethodInfo"/> from a method group </summary>
/// <param name="func">A method group</param>
/// <param name="a">A dummy parameter</param>
internal static MethodInfo FastGetMethodDefinition<T, TResult>(System.Func<T, TResult> func, T a)
{
var method = func.Method;
return method.IsGenericMethod ? method.GetGenericMethodDefinition() : method;
}
/// <summary> Get a <see cref="MethodInfo"/> from a method group </summary>
/// <param name="func">A method group</param>
/// <param name="a1">A dummy parameter</param>
/// <param name="a2">A dummy parameter</param>
internal static MethodInfo FastGetMethodDefinition<T1, T2, TResult>(System.Func<T1, T2, TResult> func, T1 a1, T2 a2)
{
var method = func.Method;
return method.IsGenericMethod ? method.GetGenericMethodDefinition() : method;
}
/// <summary> Get a <see cref="MethodInfo"/> from a method group </summary>
/// <param name="func">A method group</param>
/// <param name="a1">A dummy parameter</param>
/// <param name="a2">A dummy parameter</param>
/// <param name="a3">A dummy parameter</param>
internal static MethodInfo FastGetMethodDefinition<T1, T2, T3, TResult>(System.Func<T1, T2, T3, TResult> func, T1 a1, T2 a2, T3 a3)
{
var method = func.Method;
return method.IsGenericMethod ? method.GetGenericMethodDefinition() : method;
}
/// <summary> Get a <see cref="MethodInfo"/> from a method group </summary>
/// <param name="func">A method group</param>
/// <param name="a1">A dummy parameter</param>
/// <param name="a2">A dummy parameter</param>
/// <param name="a3">A dummy parameter</param>
/// <param name="a4">A dummy parameter</param>
internal static MethodInfo FastGetMethodDefinition<T1, T2, T3, T4, TResult>(System.Func<T1, T2, T3, T4, TResult> func, T1 a1, T2 a2, T3 a3, T4 a4)
{
var method = func.Method;
return method.IsGenericMethod ? method.GetGenericMethodDefinition() : method;
}
/// <summary> Get a <see cref="MethodInfo"/> from a method group </summary>
/// <param name="func">A method group</param>
/// <param name="a1">A dummy parameter</param>
/// <param name="a2">A dummy parameter</param>
/// <param name="a3">A dummy parameter</param>
/// <param name="a4">A dummy parameter</param>
/// <param name="a5">A dummy parameter</param>
internal static MethodInfo FastGetMethodDefinition<T1, T2, T3, T4, T5, TResult>(System.Func<T1, T2, T3, T4, T5, TResult> func, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5)
{
var method = func.Method;
return method.IsGenericMethod ? method.GetGenericMethodDefinition() : method;
}
/// <summary>
/// Get the <see cref="MethodInfo"/> for a public overload of a given method if the method does not match
/// given parameter types, otherwise directly yield the given method.
/// </summary>
/// <param name="method">The method for which finding an overload.</param>
/// <param name="parameterTypes">The arguments types of the overload to get.</param>
/// <returns>The <see cref="MethodInfo"/> of the method.</returns>
/// <remarks>Whenever possible, use GetMethod() instead for performance reasons.</remarks>
public static MethodInfo GetMethodOverload(MethodInfo method, params System.Type[] parameterTypes)
{
if (method == null)
throw new ArgumentNullException(nameof(method));
if (parameterTypes == null)
throw new ArgumentNullException(nameof(parameterTypes));
if (ParameterTypesMatch(method.GetParameters(), parameterTypes))
return method;
var overload = method.DeclaringType.GetMethod(method.Name,
(method.IsStatic ? BindingFlags.Static : BindingFlags.Instance) | BindingFlags.Public,
null, parameterTypes, null);
if (overload == null)
throw new InvalidOperationException(
$"No overload found for method '{method.DeclaringType.Name}.{method.Name}' and parameter types '{string.Join(", ", parameterTypes.Select(t => t.Name))}'");
return overload;
}
/// <summary>
/// Gets the field or property to be accessed.
/// </summary>
/// <typeparam name="TSource">The declaring-type of the property.</typeparam>
/// <typeparam name="TResult">The type of the property.</typeparam>
/// <param name="property">The expression representing the property getter.</param>
/// <returns>The <see cref="MemberInfo"/> of the property.</returns>
public static MemberInfo GetProperty<TSource, TResult>(Expression<Func<TSource, TResult>> property)
{
if (property == null)
{
throw new ArgumentNullException(nameof(property));
}
return ((MemberExpression)property.Body).Member;
}
/// <summary>
/// Gets the static field or property to be accessed.
/// </summary>
/// <typeparam name="TResult">The type of the property.</typeparam>
/// <param name="property">The expression representing the property getter.</param>
/// <returns>The <see cref="MemberInfo"/> of the property.</returns>
public static MemberInfo GetProperty<TResult>(Expression<Func<TResult>> property)
{
if (property == null)
{
throw new ArgumentNullException(nameof(property));
}
return ((MemberExpression)property.Body).Member;
}
internal static bool ParameterTypesMatch(ParameterInfo[] parameters, System.Type[] types)
{
if (parameters.Length != types.Length)
{
return false;
}
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i].ParameterType == types[i])
{
continue;
}
if (parameters[i].ParameterType.ContainsGenericParameters && types[i].ContainsGenericParameters &&
parameters[i].ParameterType.GetGenericArguments().Length == types[i].GetGenericArguments().Length)
{
continue;
}
return false;
}
return true;
}
internal static System.Type GetPropertyOrFieldType(this MemberInfo memberInfo)
{
if (memberInfo is PropertyInfo propertyInfo)
{
return propertyInfo.PropertyType;
}
if (memberInfo is FieldInfo fieldInfo)
{
return fieldInfo.FieldType;
}
return null;
}
/// <summary>
/// Determine if the specified <see cref="System.Type"/> overrides the
/// implementation of Equals from <see cref="Object"/>
/// </summary>
/// <param name="clazz">The <see cref="System.Type"/> to reflect.</param>
/// <returns><see langword="true" /> if any type in the hierarchy overrides Equals(object).</returns>
public static bool OverridesEquals(System.Type clazz)
{
return OverrideMethod(clazz, "Equals", new[] { typeof(object) });
}
private static bool OverrideMethod(System.Type clazz, string methodName, System.Type[] parametersTypes)
{
try
{
MethodInfo method = !clazz.IsInterface
? clazz.GetMethod(methodName, parametersTypes)
: GetMethodFromInterface(clazz, methodName, parametersTypes);
if (method == null)
{
return false;
}
else
{
// make sure that the DeclaringType is not System.Object - if that is the
// declaring type then there is no override.
return !(method.DeclaringType == typeof(object));
}
}
catch (AmbiguousMatchException)
{
// an ambiguous match means that there is an override and it
// can't determine which one to use.
return true;
}
}
private static MethodInfo GetMethodFromInterface(System.Type type, string methodName, System.Type[] parametersTypes)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly;
if (type == null)
{
return null;
}
MethodInfo method = type.GetMethod(methodName, flags, null, parametersTypes, null);
if (method == null)
{
System.Type[] interfaces = type.GetInterfaces();
foreach (var @interface in interfaces)
{
method = GetMethodFromInterface(@interface, methodName, parametersTypes);
if (method != null)
{
return method;
}
}
}
return method;
}
/// <summary>
/// Determine if the specified <see cref="System.Type"/> overrides the
/// implementation of GetHashCode from <see cref="Object"/>
/// </summary>
/// <param name="clazz">The <see cref="System.Type"/> to reflect.</param>
/// <returns><see langword="true" /> if any type in the hierarchy overrides GetHashCode().</returns>
public static bool OverridesGetHashCode(System.Type clazz)
{
return OverrideMethod(clazz, "GetHashCode", System.Type.EmptyTypes);
}
/// <summary>
/// Finds the <see cref="IGetter"/> for the property in the <see cref="System.Type"/>.
/// </summary>
/// <param name="theClass">The <see cref="System.Type"/> to find the property in.</param>
/// <param name="propertyName">The name of the Property to find.</param>
/// <param name="propertyAccessorName">The name of the property access strategy.</param>
/// <returns>The <see cref="IGetter"/> to get the value of the Property.</returns>
/// <remarks>
/// This one takes a propertyAccessor name as we might know the correct strategy by now so we avoid Exceptions which are costly
/// </remarks>
public static IGetter GetGetter(System.Type theClass, string propertyName, string propertyAccessorName)
{
return PropertyAccessorFactory
.GetPropertyAccessor(propertyAccessorName)
.GetGetter(theClass, propertyName);
}
/// <summary>
/// Get the NHibernate <see cref="IType" /> for the named property of the <see cref="System.Type"/>.
/// </summary>
/// <param name="theClass">The <see cref="System.Type"/> to find the Property in.</param>
/// <param name="name">The name of the property/field to find in the class.</param>
/// <param name="access">The name of the property accessor for the property.</param>
/// <returns>
/// The NHibernate <see cref="IType"/> for the named property.
/// </returns>
public static IType ReflectedPropertyType(System.Type theClass, string name, string access)
{
System.Type propertyClass = ReflectedPropertyClass(theClass, name, access);
var heuristicClass = propertyClass.UnwrapIfNullable();
return TypeFactory.HeuristicType(heuristicClass);
}
/// <summary>
/// Get the <see cref="System.Type" /> for the named property of a type.
/// </summary>
/// <param name="theClass">The <see cref="System.Type"/> to find the property in.</param>
/// <param name="name">The name of the property/field to find in the class.</param>
/// <param name="access">The name of the property accessor for the property.</param>
/// <returns>The <see cref="System.Type" /> for the named property.</returns>
public static System.Type ReflectedPropertyClass(System.Type theClass, string name, string access)
{
return GetGetter(theClass, name, access).ReturnType;
}
/// <summary>
/// Get the <see cref="System.Type" /> for the named property of a type.
/// </summary>
/// <param name="className">The FullName to find the property in.</param>
/// <param name="name">The name of the property/field to find in the class.</param>
/// <param name="accessorName">The name of the property accessor for the property.</param>
/// <returns>The <see cref="System.Type" /> for the named property.</returns>
public static System.Type ReflectedPropertyClass(string className, string name, string accessorName)
{
try
{
System.Type clazz = ClassForName(className);
return GetGetter(clazz, name, accessorName).ReturnType;
}
catch (Exception cnfe)
{
throw new MappingException(string.Format("class {0} not found while looking for property: {1}", className, name), cnfe);
}
}
/// <summary>
/// Returns a reference to the Type.
/// </summary>
/// <param name="name">The name of the class or a fully qualified name.</param>
/// <returns>The Type for the Class.</returns>
public static System.Type ClassForName(string name)
{
AssemblyQualifiedTypeName parsedName = TypeNameParser.Parse(name);
System.Type result = TypeFromAssembly(parsedName, true);
return result;
}
/// <summary>
/// Load a System.Type given its name.
/// </summary>
/// <param name="classFullName">The class FullName or AssemblyQualifiedName</param>
/// <returns>The System.Type</returns>
/// <remarks>
/// If the <paramref name="classFullName"/> don't represent an <see cref="System.Type.AssemblyQualifiedName"/>
/// the method try to find the System.Type scanning all Assemblies of the <see cref="AppDomain.CurrentDomain"/>.
/// </remarks>
/// <exception cref="TypeLoadException">If no System.Type was found for <paramref name="classFullName"/>.</exception>
public static System.Type ClassForFullName(string classFullName)
{
var result = ClassForFullNameOrNull(classFullName);
if (result == null)
{
string message = "Could not load type " + classFullName + ". Possible cause: the assembly was not loaded or not specified.";
throw new TypeLoadException(message);
}
return result;
}
/// <summary>
/// Load a System.Type given its name.
/// </summary>
/// <param name="classFullName">The class FullName or AssemblyQualifiedName</param>
/// <returns>The System.Type or null</returns>
/// <remarks>
/// If the <paramref name="classFullName"/> don't represent an <see cref="System.Type.AssemblyQualifiedName"/>
/// the method try to find the System.Type scanning all Assemblies of the <see cref="AppDomain.CurrentDomain"/>.
/// </remarks>
public static System.Type ClassForFullNameOrNull(string classFullName)
{
System.Type result = null;
AssemblyQualifiedTypeName parsedName = TypeNameParser.Parse(classFullName);
if (!string.IsNullOrEmpty(parsedName.Assembly))
{
result = TypeFromAssembly(parsedName, false);
}
else
{
if (!string.IsNullOrEmpty(classFullName))
{
Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly a in ass)
{
result = a.GetType(classFullName, false, false);
if (result != null)
break; //<<<<<================
}
}
}
return result;
}
public static System.Type TypeFromAssembly(string type, string assembly, bool throwIfError)
{
return TypeFromAssembly(new AssemblyQualifiedTypeName(type, assembly), throwIfError);
}
/// <summary>
/// Returns a <see cref="System.Type"/> from an already loaded Assembly or an
/// Assembly that is loaded with a partial name.
/// </summary>
/// <param name="name">An <see cref="AssemblyQualifiedTypeName" />.</param>
/// <param name="throwOnError"><see langword="true" /> if an exception should be thrown
/// in case of an error, <see langword="false" /> otherwise.</param>
/// <returns>
/// A <see cref="System.Type"/> object that represents the specified type,
/// or <see langword="null" /> if the type cannot be loaded.
/// </returns>
/// <remarks>
/// Attempts to get a reference to the type from an already loaded assembly. If the
/// type cannot be found then the assembly is loaded using
/// <see cref="Assembly.Load(string)" />.
/// </remarks>
public static System.Type TypeFromAssembly(AssemblyQualifiedTypeName name, bool throwOnError)
{
try
{
// Try to get the type from an already loaded assembly
System.Type type = System.Type.GetType(name.ToString());
if (type != null)
{
return type;
}
if (name.Assembly == null)
{
// No assembly was specified for the type, so just fail
const string noAssembly = "Could not load type {0}. Possible cause: no assembly name specified.";
log.Warn(noAssembly, name);
if (throwOnError) throw new TypeLoadException(string.Format(noAssembly, name));
return null;
}
//Load type from already loaded assembly
type = System.Type.GetType(
name.ToString(),
an => AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == an.FullName),
null);
if (type != null)
{
return type;
}
Assembly assembly = Assembly.Load(name.Assembly);
if (assembly == null)
{
log.Warn("Could not load type {0}. Possible cause: incorrect assembly name specified.", name);
return null;
}
type = assembly.GetType(name.Type, throwOnError);
if (type == null)
{
log.Warn("Could not load type {0}.", name);
return null;
}
return type;
}
catch (Exception e)
{
if (log.IsErrorEnabled())
{
log.Error(e, "Could not load type {0}.", name);
}
if (throwOnError) throw;
return null;
}
}
public static bool TryLoadAssembly(string assemblyName)
{
if (string.IsNullOrEmpty(assemblyName))
return false;
bool result = true;
try
{
Assembly.Load(assemblyName);
}
catch (Exception)
{
result = false;
}
return result;
}
/// <summary>
/// Returns the value of the static field <paramref name="fieldName"/> of <paramref name="type"/>.
/// </summary>
/// <param name="type">The <see cref="System.Type"/> .</param>
/// <param name="fieldName">The name of the field in the <paramref name="type"/>.</param>
/// <returns>The value contained in the field, or <see langword="null" /> if the type or the field does not exist.</returns>
public static object GetConstantValue(System.Type type, string fieldName)
{
try
{
FieldInfo field = type.GetField(fieldName);
if (field == null)
{
return null;
}
return field.GetValue(null);
}
catch
{
return null;
}
}
/// <summary>
/// Gets the default no arg constructor for the <see cref="System.Type"/>.
/// </summary>
/// <param name="type">The <see cref="System.Type"/> to find the constructor for.</param>
/// <returns>
/// The <see cref="ConstructorInfo"/> for the no argument constructor, or <see langword="null" /> if the
/// <c>type</c> is an abstract class.
/// </returns>
/// <exception cref="InstantiationException">
/// Thrown when there is a problem calling the method GetConstructor on <see cref="System.Type"/>.
/// </exception>
public static ConstructorInfo GetDefaultConstructor(System.Type type)
{
if (IsAbstractClass(type))
return null;
try
{
ConstructorInfo constructor =
type.GetConstructor(AnyVisibilityInstance, null, CallingConventions.HasThis, NoClasses, null);
return constructor;
}
catch (Exception e)
{
throw new InstantiationException("A default (no-arg) constructor could not be found for: ", e, type);
}
}
/// <summary>
/// Finds the constructor that takes the parameters.
/// </summary>
/// <param name="type">The <see cref="System.Type"/> to find the constructor in.</param>
/// <param name="types">The <see cref="IType"/> objects to use to find the appropriate constructor.</param>
/// <returns>
/// An <see cref="ConstructorInfo"/> that can be used to create the type with
/// the specified parameters.
/// </returns>
/// <exception cref="InstantiationException">
/// Thrown when no constructor with the correct signature can be found.
/// </exception>
public static ConstructorInfo GetConstructor(System.Type type, IType[] types)
{
ConstructorInfo[] candidates = type.GetConstructors(AnyVisibilityInstance);
foreach (ConstructorInfo constructor in candidates)
{
ParameterInfo[] parameters = constructor.GetParameters();
if (parameters.Length == types.Length)
{
bool found = true;
for (int j = 0; j < parameters.Length; j++)
{
bool ok = parameters[j].ParameterType.IsAssignableFrom(
types[j].ReturnedClass);
if (!ok)
{
found = false;
break;
}
}
if (found)
{
return constructor;
}
}
}
throw new InstantiationException(FormatConstructorNotFoundMessage(types), null, type);
}
private static string FormatConstructorNotFoundMessage(IEnumerable<IType> types)
{
var result = new StringBuilder("no constructor compatible with (");
bool first = true;
foreach (IType type in types)
{
if (!first)
{
result.Append(", ");
}
first = false;
result.Append(type.ReturnedClass);
}
result.Append(") found in class: ");
return result.ToString();
}
/// <summary>
/// Determines if the <see cref="System.Type"/> is a non creatable class.
/// </summary>
/// <param name="type">The <see cref="System.Type"/> to check.</param>
/// <returns><see langword="true" /> if the <see cref="System.Type"/> is an Abstract Class or an Interface.</returns>
public static bool IsAbstractClass(System.Type type)
{
return (type.IsAbstract || type.IsInterface);
}
public static bool IsFinalClass(System.Type type)
{
return type.IsSealed;
}
/// <summary>
/// Unwraps the supplied <see cref="System.Reflection.TargetInvocationException"/>
/// and returns the inner exception preserving the stack trace.
/// </summary>
/// <param name="ex">
/// The <see cref="System.Reflection.TargetInvocationException"/> to unwrap.
/// </param>
/// <returns>The unwrapped exception.</returns>
public static Exception UnwrapTargetInvocationException(TargetInvocationException ex)
{
Exception_InternalPreserveStackTrace.Invoke(ex.InnerException, Array.Empty<object>());
return ex.InnerException;
}
/// <summary>
/// Ensures an exception current stack-trace will be preserved if the exception is explicitly rethrown.
/// </summary>
/// <param name="ex">
/// The <see cref="Exception"/> which current stack-trace is to be preserved in case of explicit rethrow.
/// </param>
/// <returns>The unwrapped exception.</returns>
internal static void PreserveStackTrace(Exception ex)
{
Exception_InternalPreserveStackTrace.Invoke(ex, Array.Empty<object>());
}
/// <summary>
/// Try to find a method in a given type.
/// </summary>
/// <param name="type">The given type.</param>
/// <param name="method">The method info.</param>
/// <returns>The found method or null.</returns>
/// <remarks>
/// The <paramref name="method"/>, in general, become from another <see cref="Type"/>.
/// </remarks>
public static MethodInfo TryGetMethod(System.Type type, MethodInfo method)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (method == null)
{
return null;
}
System.Type[] tps = GetMethodSignature(method);
return SafeGetMethod(type, method, tps);
}
private static System.Type[] GetMethodSignature(MethodInfo method)
{
var pi = method.GetParameters();
var tps = new System.Type[pi.Length];
for (int i = 0; i < pi.Length; i++)
{
tps[i] = pi[i].ParameterType;
}
return tps;
}
private static MethodInfo SafeGetMethod(System.Type type, MethodInfo method, System.Type[] tps)
{
const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
List<System.Type> typesToSearch = new List<System.Type>();
MethodInfo foundMethod = null;
typesToSearch.Add(type);
if (type.IsInterface)
{
// Methods on parent interfaces are not actually inherited
// by child interfaces, so we have to use GetInterfaces to
// identify any parent interfaces that may contain the
// method implementation
System.Type[] inheritedInterfaces = type.GetInterfaces();
typesToSearch.AddRange(inheritedInterfaces);
}
foreach (System.Type typeToSearch in typesToSearch)
{
MethodInfo result = typeToSearch.GetMethod(method.Name, bindingFlags, null, tps, null);
if (result != null)
{
foundMethod = result;
break;
}
}
return foundMethod;
}
internal static object GetConstantValue(string qualifiedName)
{
return GetConstantValue(qualifiedName, null);
}
internal static object GetConstantValue(string qualifiedName, ISessionFactoryImplementor sfi)
{
string className = StringHelper.Qualifier(qualifiedName);
if (!string.IsNullOrEmpty(className))
{
System.Type t = System.Type.GetType(className);
if (t == null && sfi != null)
{
t = System.Type.GetType(sfi.GetImportedClassName(className));
}
if (t != null)
{
return GetConstantValue(t, StringHelper.Unqualify(qualifiedName));
}
}
return null;
}
// Since v5
[Obsolete("Please use GetMethodDefinition then MethodInfo.MakeGenericMethod instead")]
public static MethodInfo GetGenericMethodFrom<T>(string methodName, System.Type[] genericArgs, System.Type[] signature)
{
MethodInfo result = null;
MethodInfo[] methods = typeof(T).GetMethods();
foreach (var method in methods)
{
if (method.Name.Equals(methodName) && method.IsGenericMethod
&& signature.Length == method.GetParameters().Length
&& method.GetGenericArguments().Length == genericArgs.Length)
{
bool foundCandidate = true;
result = method.MakeGenericMethod(genericArgs);
ParameterInfo[] ms = result.GetParameters();
for (int i = 0; i < signature.Length; i++)
{
if (ms[i].ParameterType != signature[i])
{
foundCandidate = false;
}
}
if (foundCandidate)
{
return result;
}
}
}
return result;
}
public static IDictionary<string, string> ToTypeParameters(this object source)
{
if (source == null)
{
return new Dictionary<string, string>(1);
}
var props = source.GetType().GetProperties();
if (props.Length == 0)
{
return new Dictionary<string, string>(1);
}
var result = new Dictionary<string, string>(props.Length);
foreach (var prop in props)
{
var value = prop.GetValue(source, null);
if (!ReferenceEquals(null, value))
{
result[prop.Name] = value.ToString();
}
}
return result;
}
public static bool IsPropertyGet(MethodInfo method)
{
return method.IsSpecialName && method.Name.StartsWith("get_", StringComparison.Ordinal);
}
public static bool IsPropertySet(MethodInfo method)
{
return method.IsSpecialName && method.Name.StartsWith("set_", StringComparison.Ordinal);
}
public static string GetPropertyName(MethodInfo method)
{
return method.Name.Substring(4);
}
public static System.Type GetCollectionElementType(this IEnumerable collectionInstance)
{
if (collectionInstance == null)
{
throw new ArgumentNullException("collectionInstance");
}
var collectionType = collectionInstance.GetType();
return GetCollectionElementType(collectionType);
}
public static System.Type GetCollectionElementType(System.Type collectionType)
{
if (collectionType == null)
{
throw new ArgumentNullException("collectionType");
}
if (collectionType.IsArray)
{
return collectionType.GetElementType();
}
if (collectionType.IsGenericType)
{
List<System.Type> interfaces = collectionType.GetInterfaces().Where(t => t.IsGenericType).ToList();
if (collectionType.IsInterface)
{
interfaces.Add(collectionType);
}
var enumerableInterface = interfaces.FirstOrDefault(t => t.GetGenericTypeDefinition() == typeof (IEnumerable<>));
if (enumerableInterface != null)
{
return enumerableInterface.GetGenericArguments()[0];
}
}
return null;
}
/// <summary>
/// Try to find a property, that can be managed by NHibernate, from a given type.
/// </summary>
/// <param name="source">The given <see cref="System.Type"/>. </param>
/// <param name="propertyName">The name of the property to find.</param>
/// <returns>true if the property exists; otherwise false.</returns>
/// <remarks>
/// When the user defines a field.xxxxx access strategy should be because both the property and the field exists.
/// NHibernate can work even when the property does not exist but in this case the user should use the appropriate accessor.
/// </remarks>
public static bool HasProperty(this System.Type source, string propertyName)
{
if (source == typeof (object) || source == null)
{
return false;
}
if (string.IsNullOrEmpty(propertyName))
{
return false;
}
PropertyInfo property = source.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
if (property != null)
{
return true;
}
return HasProperty(source.BaseType, propertyName) || source.GetInterfaces().Any(@interface => HasProperty(@interface, propertyName));
}
/// <summary>
/// Check if a method is declared in a given <see cref="System.Type"/>.
/// </summary>
/// <param name="source">The method to check.</param>
/// <param name="realDeclaringType">The where the method is really declared.</param>
/// <returns>True if the method is an implementation of the method declared in <paramref name="realDeclaringType"/>; false otherwise. </returns>
public static bool IsMethodOf(this MethodInfo source, System.Type realDeclaringType)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (realDeclaringType == null)
{