1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.guice.type;
17
18 import com.google.inject.Injector;
19 import com.google.inject.TypeLiteral;
20
21 import jakarta.inject.Inject;
22 import jakarta.inject.Provider;
23
24 import java.lang.reflect.Constructor;
25 import java.util.Objects;
26
27 import org.apache.ibatis.type.TypeException;
28 import org.apache.ibatis.type.TypeHandler;
29
30
31
32
33 public final class TypeHandlerProvider<TH extends TypeHandler<? extends T>, T> implements Provider<TH> {
34 private final TypeLiteral<TH> typeHandlerTypeLiteral;
35 private final Class<T> handledType;
36 @Inject
37 private Injector injector;
38
39 public TypeHandlerProvider(Class<TH> typeHandlerType, Class<T> handledType) {
40 this.typeHandlerTypeLiteral = TypeLiteral.get(typeHandlerType);
41 this.handledType = handledType;
42 }
43
44 public TypeHandlerProvider(TypeLiteral<TH> typeHandlerType, Class<T> handledType) {
45 this.typeHandlerTypeLiteral = typeHandlerType;
46 this.handledType = handledType;
47 }
48
49 TypeHandlerProvider(Injector injector, Class<TH> typeHandlerType, Class<T> handledType) {
50 this(typeHandlerType, handledType);
51 this.injector = injector;
52 }
53
54 TypeHandlerProvider(Injector injector, TypeLiteral<TH> typeHandlerType, Class<T> handledType) {
55 this(typeHandlerType, handledType);
56 this.injector = injector;
57 }
58
59 @Override
60 @SuppressWarnings("unchecked")
61 public TH get() {
62 TH instance = null;
63 if (handledType != null) {
64 try {
65 Constructor<?> c = typeHandlerTypeLiteral.getRawType().getConstructor(Class.class);
66 instance = (TH) c.newInstance(handledType);
67 injector.injectMembers(instance);
68 } catch (NoSuchMethodException ignored) {
69
70 } catch (Exception e) {
71 throw new TypeException("Failed invoking constructor for handler " + typeHandlerTypeLiteral.getType(), e);
72 }
73 }
74 if (instance == null) {
75 try {
76 instance = (TH) typeHandlerTypeLiteral.getRawType().newInstance();
77 injector.injectMembers(instance);
78 } catch (Exception e) {
79 throw new TypeException("Failed invoking constructor for handler " + typeHandlerTypeLiteral.getType(), e);
80 }
81 }
82 return instance;
83 }
84
85 @Override
86 public int hashCode() {
87 return Objects.hash(this.typeHandlerTypeLiteral, this.handledType);
88 }
89
90 @Override
91 public boolean equals(Object obj) {
92 if (obj == null) {
93 return false;
94 }
95 if (this.getClass() != obj.getClass()) {
96 return false;
97 }
98 TypeHandlerProvider other = (TypeHandlerProvider) obj;
99 return Objects.equals(this.typeHandlerTypeLiteral, other.typeHandlerTypeLiteral)
100 && Objects.equals(this.handledType, other.handledType);
101 }
102 }