-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMvReflection.java
More file actions
298 lines (272 loc) · 11.6 KB
/
MvReflection.java
File metadata and controls
298 lines (272 loc) · 11.6 KB
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
/*
* AndroidWithoutStupid Java Library
* Created by V. Subhash
* http://www.VSubhash.com
* Released as Public Domain Software in 2014
*/
package com.vsubhash.droid.androidwithoutstupid;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import com.vsubhash.droid.androidwithoutstupid.MvMessages;
/**
* This class makes it easy to use Java reflection to invoke APIs available
* only in higher Android SDK versions.
*
* @author V. Subhash (<a href="http://www.VSubhash.com/">www.VSubhash.com</a>)
* @version 2015.10.10
*/
public class MvReflection {
private MvReflection() {
super();
}
/**
* Creates a new instance of a class with specified name. This method will
* invoke a constructor with specified arguments. If it returns a null, it
* means that the class or the constructor is not available in the SDK version
* of the device.
*
* @param asClassName
* full canonical name of the class
* @param aoConstructorArguments
* arguments passed to the constructor
* @return new class instance if successful; null if otherwise
*/
@SuppressWarnings("rawtypes")
static public Object getNewInstance(String asClassName, Object... aoConstructorArguments) {
Object oReturnedInstance = null;
try {
Class oClass = Class.forName(asClassName);
if (aoConstructorArguments == null) {
Constructor[] oClassConstructors = oClass.getConstructors();
for (Constructor oClassConstructor: oClassConstructors) {
if (oClassConstructor.getParameterTypes().length == 0) {
oReturnedInstance = oClassConstructor.newInstance(new Object[0]);
break;
}
}
} else {
ArrayList<Class> oConstructorArgumentsClassesList = new ArrayList<Class>();
for (Object oObject: aoConstructorArguments) {
oConstructorArgumentsClassesList.add(oObject.getClass());
}
Constructor oClassConstructor = oClass.getConstructor(oConstructorArgumentsClassesList.toArray(new Class[] { }));
oReturnedInstance = oClassConstructor.newInstance(aoConstructorArguments);
}
} catch (ClassNotFoundException e) {
MvMessages.logMessage("Error: getNewInstance() raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (IllegalArgumentException e) {
MvMessages.logMessage("Error: getNewInstance() raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (InstantiationException e) {
MvMessages.logMessage("Error: getNewInstance() raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (IllegalAccessException e) {
MvMessages.logMessage("Error: getNewInstance() raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (InvocationTargetException e) {
MvMessages.logMessage("Error: getNewInstance() raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (SecurityException e) {
MvMessages.logMessage("Error: getNewInstance() raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (NoSuchMethodException e) {
MvMessages.logMessage("Error: getNewInstance() raised " + e.getClass().getCanonicalName() + " - " + e.getMessage());
// e.printStackTrace();
}
return(oReturnedInstance);
}
/**
* Creates a new instance of a class with specified name in the class of the
* specified instance. This method will invoke a constructor with specified
* arguments. If it returns a null, it means that the class or the constructor
* is not available in the SDK version of the device. As nested class
* instances cannot be created unless the enclosing class instance is
* provided, pass an enclosing class instance after creating it first using
* the {@link #getNewInstance(String, Object...)} method. Remember that each
* level of the nesting needs to be delimited by a '$'. For example:
* <code>android.graphics.pdf.PdfDocument$PageInfo$Builder</code> As Java
* reflection will not match arguments from base-class types or derived-class
* types, this method will attempt to iterate through whatever constructors it
* finds and create an instance with the the first constructor with which it
* succeeds.
*
* @param oEnclosingInstance
* an instance of the enclosing class of the nested class
* @param asClassName
* full canonical name of the class instance
* @param aoConstructorArguments
* arguments passed to the constructor
* @return new class instance if successful; null if otherwise
*/
@SuppressWarnings({ "rawtypes", "static-access" })
static public Object getNewNestedInstance(Object oEnclosingInstance, String asClassName, Object... aoConstructorArguments) {
Object oReturnedInstance = null;
try {
Class oClass = oEnclosingInstance.getClass().forName(asClassName);
if (aoConstructorArguments == null) {
Constructor[] oClassConstructors = oClass.getConstructors();
for (Constructor oClassConstructor: oClassConstructors) {
// Find the zero-argument constructor
if (oClassConstructor.getParameterTypes().length == 0) {
try {
oReturnedInstance = oClassConstructor.newInstance(new Object[0]);
break;
} catch (IllegalArgumentException e) {
MvMessages.logMessage("Error: getNewNestedInstance(Object, String, Object...) raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (InstantiationException e) {
MvMessages.logMessage("Error: getNewNestedInstance(Object, String, Object...) raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (IllegalAccessException e) {
MvMessages.logMessage("Error: getNewNestedInstance(Object, String, Object...) raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (InvocationTargetException e) {
MvMessages.logMessage("Error: getNewNestedInstance(Object, String, Object...) raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
}
}
}
} else {
// Create a list of class types of the arguments
ArrayList<Class> oConstructorArgumentsClassesList = new ArrayList<Class>();
for (Object oObject: aoConstructorArguments) {
MvMessages.logMessage("here" + oObject.getClass().getCanonicalName());
oConstructorArgumentsClassesList.add(oObject.getClass());
}
try {
// This getConstructor() method may fail easily, as it requires an
// exact match.
Constructor oClassConstructor = oClass.getConstructor(oConstructorArgumentsClassesList.toArray(new Class[] { }));
oReturnedInstance = oClassConstructor.newInstance(aoConstructorArguments);
} catch (Exception e) { // No such constructor exists
// Brute force method - find the first constructor that succeeds with
// the given arguments. When base class types of the arguments match
// those of a constructor, a new instance may get created.
for (Constructor oClassConstructor: oClass.getConstructors()) {
try {
oReturnedInstance = oClassConstructor.newInstance(aoConstructorArguments);
MvMessages.logMessage("We have a winner: " + oClassConstructor.toGenericString());
break;
} catch(Exception e1) {
MvMessages.logMessage("A constructor failed: " + oClassConstructor.toGenericString());
}
}
}
}
} catch (ClassNotFoundException e) {
MvMessages.logMessage("Error: getNewNestedInstance(Object, String, Object...) raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
}
return(oReturnedInstance);
}
/**
* Use specified class instance and execute its method with specified name and
* arguments.
*
* @param aoInvokingInstance
* instance whose method needs to be called
* @param asMethodName
* name of the method
* @param aoMethodArguments
* arguments passed to the method
* @return any value returned by the method; null if the method does not exist
* or if its return type is void
*/
@SuppressWarnings("rawtypes")
static public Object invokeMethod(Object aoInvokingInstance, String asMethodName, Object... aoMethodArguments) {
Object oReturnedInstance = null;
ArrayList<Class> oArgsClassesList = new ArrayList<Class>();
if (aoMethodArguments != null) {
for (Object oObject : aoMethodArguments) {
oArgsClassesList.add(oObject.getClass());
}
}
try {
// This getMethod() method may fail easily as it requires an exact match.
Method oMethod = aoInvokingInstance.getClass().getMethod(asMethodName, oArgsClassesList.toArray(new Class[] {}));
oReturnedInstance = oMethod.invoke(aoInvokingInstance, aoMethodArguments);
} catch (SecurityException e) {
MvMessages.logMessage(e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (NoSuchMethodException e) {
// Brute force tactic - find the first method overload that succeeds
// with the given arguments. When the base types of the arguments
// match those of a method overload, the invocation may succeed.
for (Method oCurrentMethod : aoInvokingInstance.getClass().getMethods()) {
if (oCurrentMethod.getName().contentEquals(asMethodName)) {
if (oCurrentMethod.getParameterTypes().length == aoMethodArguments.length) {
try {
oReturnedInstance = oCurrentMethod.invoke(aoInvokingInstance, aoMethodArguments);
MvMessages.logMessage("We have a winner: " + oCurrentMethod.toGenericString());
break;
} catch (Exception e1) {
MvMessages.logMessage("A method failed:" + oCurrentMethod.toGenericString());
// e.printStackTrace();
}
}
}
}
} catch (IllegalArgumentException e) {
MvMessages.logMessage("Error: invokeMethod(Object, String, Object...) raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (IllegalAccessException e) {
MvMessages.logMessage("Error: invokeMethod(Object, String, Object...) raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
} catch (InvocationTargetException e) {
MvMessages.logMessage("Error: invokeMethod(Object, String, Object...) raised " + e.getClass().getCanonicalName());
// e.printStackTrace();
}
return(oReturnedInstance);
}
/**
* Returns int value of specified field in the class of specified instance.
*
* @param asFieldName
* name of the field
* @param aoInstance
* instance in whose class the field needs to be found
* @return result of the operation
*/
public static MvException getFieldAsInt(String asFieldName, Object aoInstance) {
MvException oResult = new MvException();
for (Field oField : aoInstance.getClass().getFields()) {
MvMessages.logMessage(oField.getName());
if (oField.getName().contentEquals(asFieldName)) {
try {
oResult.moResult = oField.getInt(aoInstance);
oResult.mbSuccess = true;
} catch (IllegalArgumentException e) {
oResult.mException = e;
} catch (IllegalAccessException e) {
oResult.mException = e;
}
break;
}
}
return(oResult);
}
/**
* Returns a field with specified name in the class of specified instance.
*
* @param asFieldName
* name of the field
* @param aoInstance
* instance in whose class the field needs to be found
* @return the field if successful; null otherwise
*/
public static Field getField(String asFieldName, Object aoInstance) {
Field oReturn = null;
for (Field oField : aoInstance.getClass().getDeclaredFields()) {
MvMessages.logMessage(oField.getName());
if (oField.getName().contentEquals(asFieldName)) {
oReturn = oField;
break;
}
}
return(oReturn);
}
}