Java Reflection Made Easy
java(at sentence-end, falling tone) indicates a confident conclusionreflectionIntroducing utility classes for easy access to the API.
What is reflection?
Reflection APIis the "thejava.lang.reflect” included in the package,
This is an API that retrieves information such as fields and methods from Java classes.
The following classes are mainly used.
- Class
- Constructor
- Method
- Field
reflectionBy using , you can create classes or call methods without having to code them directly.
You can create a class instance from a string or execute a method.
By writing the definitions of class names and method names in external files such as XML, you can dynamically adapt the application to changes in the environment during runtime.
It is also a very effective API for building highly flexible applications.
Purpose of Reflection
reflectionis not often used directly by users,
It is widely used in web applications such as Struts and frameworks such as O/R mapping.
For example, when automatically setting web screen input data to JavaBeans properties,
It is used when issuing SQL that automatically updates based on JavaBeans properties.
In addition, functions such as dynamically loading and registering plug-ins that extend functionality at application startup arereflectionThis can be easily achieved by using the
Sample Execution
Now, please run the sample and experience framework-like programming.
The following classes are used herereflectionIt shows a simple way to use the utility.
Main.java... Class to execute
BeanUtil.javaUtility class for reflection
FreeSoft.javaThe class representing FreeSoff is used as a reflection.
When executed as usual
FreeSoft freeSoft = new FreeSoft();
freeSoft.setName("Chat&Messenger Chat and Messenger!!!");
freeSoft.showName(); freeSoft.
freeSoft.showPrice(0); freeSoft.
When executed using reflection
// Instance creation of the FreeSoft class
Object invokeObject = BeanUtil.newInstance("FreeSoft"));
// Set a value in the name field.
BeanUtil.setProperty(invokeObject,. "name". , "Chat&Messenger Chat and Messenger!");
// FreeSoft's showName() method.
BeanUtil.invoke(invokeObject, invoke "showName"., null);
// Execute FreeSoft's showPrice() method.
// If the method has arguments, they must be passed in an array of type Object.
BeanUtil.invoke(invokeObject, invoke "showPrice".,new Object[]{new Integer(0)});
Execution Result
The execution result is the same in the normal case and when reflection is used.
Software name: Chat&Messenger Chat and Messenger!
Price : 0 yen
>> >> When using reflection
Software name: Chat&Messenger Chat and Messenger!
Price : 0 yen
BeanUtil method details
newInstance
public static Object newInstance(String className) throws Exception
- Creates and returns an instance from the string "className".
-
- Parameters: A
className
- fully qualified class name- Return value: 1
- New instances of fully qualified class names
- Exceptions: The
Exception
newInstance
public static Object newInstance(String className, Object[] argObj) throws Exception
- Creates and returns an instance from the string "className".
-
- Parameters: A
className
- fully qualified class nameargObj
- Constructor Arguments- Return value: 1
- New instances of fully qualified class names
- Exceptions: The
Exception
newInstance
public static Object newInstance(Class clazz) throws Exception
- Creates and returns an instance from the class "clazz".
-
- Parameters: A
clazz
- class- Return value: 1
- New instances of clazz
- Exceptions: The
Exception
newInstance
public static Object newInstance(Class clazz, Object[] argObj) throws Exception
- Creates and returns an instance from the class "clazz".
-
- Parameters: A
clazz
- classargObj
- Constructor Arguments- Return value: 1
- New instances of clazz
- Exceptions: The
Exception
setProperty
public static void setProperty(Object invokeObject, String fieldName, String String fieldName, Object value) Object value) throws Exception
- Call the setter method of the field "fieldName" of the object "invokeObject" and store the value "value".
If there is no setter method, the value will be set directly to the field. However, in this case, the access modifier of the target property must be public.
-
- Parameters: A
invokeObject
- Objects to be executedfieldName
- Property name of the object to be executedvalue
- Value to be set- Exceptions: The
Exception
- The following exceptions occurInvocationTargetException
- If the underlying method throws an exceptionIllegalAccessException
– This Method object is Java
When language access control is implemented and the underlying method cannot be accessedNoSuchMethodException
- If the method with the specified name is not found
getProperty
public static Object getProperty(Object invokeObject, String fieldName) String fieldName) throws Exception
- Calls the getter method of the field fieldName of the object invokeObject to obtain the value.
If there is no getter method, the value will be retrieved directly from the field. However, in this case, the access modifier of the target property must be public. -
- Parameters: A
invokeObject
- Objects to be executedfieldName
- Property name of the object to be executed- Return value: 1
- Return value of getter method
- Exceptions: The
Exception
- The following exceptions occurInvocationTargetException
- If the underlying method throws an exceptionIllegalAccessException
– This Method object is Java
When language access control is implemented and the underlying method cannot be accessedNoSuchFieldException
- If the field with the specified name is not found
invoke
public static Object invoke(Object invokeObject, String callMethod, String String callMethod, String Object[] argObjects) throws InvocationTargetException, IllegalAccessException, and IllegalAccessException, NoSuchMethodException NoSuchMethodException
- Executes the method "callMethod" of the object "invokeObject".
If there is a return value, it can be obtained as an Object. -
- Parameters: A
invokeObject
- Objects to be executedcallMethod
- Name of method to be executedargObjects
- If there is an argument, pass it as an array of objects. If there are no arguments, pass null.- Return value: 1
- Return value of "callMethod" executed
- Exceptions: The
InvocationTargetException
- If the underlying method throws an exceptionIllegalAccessException
– This Method object is Java
When language access control is implemented and the underlying method cannot be accessedNoSuchMethodException
- If the method with the specified name is not found
findMethod
public static Method findMethod(Object invokeObject, String callMethod, String String callMethod, String Object[] argObjects) throws NoSuchMethodException
- Searches for the method "callMethod" of the object "invokeObject".
-
- Parameters: A
invokeObject
- Objects to be executedcallMethod
- Method name of the object to be executedargObjects
- If there is an argument, pass it as an array of objects. If there are no arguments, pass null.- Return value: 1
- Method object matching the specified argument condition
- Exceptions: The
NoSuchMethodException
- If no matching method is found, or if the name is "" or "".
setField
public static void setField(Object invokeObject, String fieldName, String String fieldName, Object value) Object value) throws IllegalAccessException, NoSuchFieldException NoSuchFieldException
- Stores the value "value" in the field name "fieldName" of the object "invokeObject" to be executed.
-
- Parameters: A
invokeObject
- Objects to be executedfieldName
- Field name of the object to be executedvalue
- Value to be set- Exceptions: The
IllegalAccessException
– The field on which the specified object is based (or its subclass or implementer)
is not an instance of the class or interface it declares, or if the unwrapping conversion failsNoSuchFieldException
- If the field with the specified name is not found
getField
public static Object getField(Object invokeObject, String fieldName) String fieldName) throws IllegalAccessException, NoSuchFieldException NoSuchFieldException
- Obtains the value of the field name "fieldName" of the object "invokeObject" to be executed.
-
- Parameters: A
invokeObject
- Objects to be executedfieldName
- Field name of the object to be executed- Return value: 1
- return value
- Exceptions: The
IllegalAccessException
– The field on which the specified object is based (or its subclass or implementer)
is not an instance of the class or interface it declares, or if the unwrapping conversion failsNoSuchFieldException
- If the field with the specified name is not found
hasField
public static boolean hasField(Object object, String fieldName) throws Exception
- Check if the object "object" declares the field name "fieldName".
-
- Parameters: A
object
- Objects to be inspectedfieldName
- Name of field to be inspected- Return value: 1
- true if declared
- Exceptions: The
Exception
getAllFields
public static java.util. getAllFields(Object object) throws Exception
-
- Parameters: A
object
–- Return value: 1
- Exceptions: The
Exception
getShortClassName
public static String getShortClassName(Object object)
- Obtains the fully unqualified class name from the object.
-
- Parameters: A
object
–- Return value: 1
getShortClassName
public static String getShortClassName(String className)
- Get the class name from the fully qualified name.
-
- Parameters: A
className
–- Return value: 1
getFieldName
public static String getFieldName(String methodName)
- Change the field name from the method name. Must conform to JavaBeans conventions.
-
- Parameters: A
methodName
–- Return value: 1
isClassExist
public static boolean isClassExist(String className)
- Verifies whether the fully qualified name "className" is an existing class name.
-
- Parameters: A
className
–- Return value: 1
getPropertyDescriptors
public static PropertyDescriptor[]. getPropertyDescriptors(Object object) throws IntrospectionException
- Returns a PropertyDescriptor holding object information for "object".
-
- Parameters: A
object
–- Return value: 1
- Exceptions: The
IntrospectionException
BeanUtil Source Code
/**
* Utility class that allows you to easily use Java's reflection API
*/
public class BeanUtil {
/** */
private static final String GET = “GET”;
/** */
private static final String SET = “SET”;
// ———————————————————-『newInstance』
/**
* Generates and returns an instance from the string "className".
* @param className fully qualified class name
* @return new instance of fully qualified class name
* @throws Exception
*/
public static Object newInstance(String className) throws Exception {
try {
return Class.forName(className).newInstance();
} catch (NoClassDefFoundError e) {
System.err.println(“NoClassDefFoundError : ” + className);
throw e;
}
}
/**
* Generates and returns an instance from the string "className".
* @param className fully qualified class name
* @param argObj constructor argument
* @return new instance of fully qualified class name
* @throws Exception
*/
public static Object newInstance(String className, Object[] argObj)
throws Exception {
Class[] argClass = new Class[argObj.length];
for (int i = 0; i < argObj.length; i++) {
argClass[i] = argObj[i].getClass();
}
Constructor c = Class.forName(className).getConstructor(argClass);
return c.newInstance(argObj);
}
/**
* Create and return an instance from class 'clazz'.
* @param clazz class
* @return new instance of clazz
* @throws Exception
*/
public static Object newInstance(Class clazz) throws Exception {
return clazz.newInstance();
}
/**
* Create and return an instance from class 'clazz'.
* @param clazz class
* @param argObj constructor argument
* @return new instance of clazz
* @throws Exception
*/
public static Object newInstance(Class clazz, Object[] argObj)
throws Exception {
Class[] argClass = new Class[argObj.length];
for (int i = 0; i < argObj.length; i++) {
argClass[i] = argObj[i].getClass();
}
Constructor c = clazz.getConstructor(argClass);
return c.newInstance(argObj);
}
// —————————————————————『Method』
/**
* Setter method of field “fieldName” of object “invokeObject”
* Call, store value 'value'.
* <br>
* If there is no setter method, set the value directly to the field.
* However, in this case, the access modifier of the target property must be public.
* @param invokeObject Object to be executed
* @param fieldName Property name of the object to be executed
* @param value value to set
* @throws Exception The following exception occurs.
* @throws InvocationTargetException if the underlying method throws an exception
* @throws IllegalAccessException If this Method object is Java
* When language access control is implemented and the underlying method cannot be accessed
* @throws NoSuchMethodException if a method with the specified name is not found
*/
public static void setProperty(Object invokeObject, String fieldName,
Object value) throws Exception {
try {
Method method = searchMethod(invokeObject, fieldName, SET);
Class[] paramClasses = method.getParameterTypes();
Object[] valueArray = null;
if (paramClasses[0].isInstance(value)) {
//Do not convert if the object to be set is a subclass of the argument class.
valueArray = new Object[] { value };
} else {
valueArray = new Object[] { convObject(value, paramClasses[0]
.getName()) };
}
method.invoke(invokeObject, valueArray);
} catch (NoSuchMethodException e) {
try {
// If there is no setter method, set it directly to the field.
setField(invokeObject, fieldName, value);
} catch (NoSuchFieldException fe) {
String errorMes = “\nClass” + getShortClassName(invokeObject)
+ “is” + “for field “” + fieldName + “”\n”
+ “There is no accessible setter method, and.”
+ “Field “” + fieldName
+ “” is also not public. ” + “”;
throw new IllegalAccessException(errorMes);
}
}
}
/**
* Getter method of field fieldName of object invokeObject
* Get the call value. <br>
* If there is no getter method, the value will be obtained directly from the field.
* However, in this case, the access modifier of the target property must be public.
* @param invokeObject Object to be executed
* @param fieldName Property name of the object to be executed
* @return return value of getter method
* @throws Exception The following exception occurs.
* @throws InvocationTargetException if the underlying method throws an exception
* @throws IllegalAccessException If this Method object is Java
* When language access control is implemented and the underlying method cannot be accessed
* @throws NoSuchFieldException if a field with the specified name is not found
*/
public static Object getProperty(Object invokeObject, String fieldName)
throws Exception {
try {
Method method = searchMethod(invokeObject, fieldName, GET);
return method.invoke(invokeObject, null);
} catch (NoSuchMethodException e) {
return getField(invokeObject, fieldName);
}
}
/**
* Executes the method "callMethod" of the object "invokeObject".
* If there is a return value, it can be obtained as an Object type.
* @param invokeObject Object to be executed
* @param callMethod Method name to be executed
* @param argObjects If there is an argument, pass it as an array of objects.
* Pass null if there is no argument.
* @return Return value of executing "callMethod"
* @throws InvocationTargetException if the underlying method throws an exception
* @throws IllegalAccessException If this Method object is Java
* When language access control is implemented and the underlying method cannot be accessed
* @throws NoSuchMethodException if a method with the specified name is not found
*/
public static Object invoke(Object invokeObject, String callMethod,
Object[] argObjects) throws InvocationTargetException,
IllegalAccessException, NoSuchMethodException {
Method method = findMethod(invokeObject, callMethod, argObjects);
return method.invoke(invokeObject, argObjects);
}
/**
* Search for method 'callMethod' of object 'invokeObject'.
* @param invokeObject Object to be executed
* @param callMethod Method name of the object to be executed
* @param argObjects If there is an argument, pass it as an array of objects.
* Pass null if there is no argument.
* @return Method object that matches the specified argument conditions
* @throws NoSuchMethodException If no matching method is found,
* Or if the name is “ " or " "in the case of
*/
public static Method findMethod(Object invokeObject, String callMethod,
Object[] argObjects) throws NoSuchMethodException {
Class[] paramClasses = null;
Method[] methods = invokeObject.getClass().getMethods();
top: for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(callMethod)) {
if (argObjects == null
&& methods[i].getParameterTypes().length == 0) {
return methods[i];
}
if (argObjects == null) {
continue;
}
paramClasses = methods[i].getParameterTypes();
if (paramClasses.length == argObjects.length) {
// Validate all parameter list types and argument types
for (int j = 0; j < paramClasses.length; j++) {
Class paramClass = paramClasses[j];
Object argObj = argObjects[j];
// If the argument type is primitive, the argument object
// is not null and is primitive
//If it's a subclass of Number, it's OK.
if (argObj == null) {
continue;
}
if (paramClass.isPrimitive()
&& (argObj instanceof Number || argObj
.getClass().isPrimitive())) {
continue;
}
if (!paramClass.isInstance(argObj)) {
// Proceed to the next method when the types are not compatible with implicit conversion
continue top;
}
}
return methods[i];
}
}
}
String paramLength = (paramClasses != null) ? Integer
.toString(paramClasses.length) : “”;
String errorMes = getShortClassName(invokeObject) + “method”
+ callMethod + “There is no.” + “[ paramClasses.length ] = ”
+ paramLength + “,[ argObjects.length ] = ” + argObjects.length
+ “”;
throw new NoSuchMethodException(errorMes);
}
// —————————————————————-『Field』
/**
* Value for field name "fieldName" of object "invokeObject" to be executed
* Stores "value".
* @param invokeObject Object to be executed
* @param fieldName Field name of object to be executed
* @param value value to set
* @throws IllegalAccessException If the specified object is
* field (or its subclass or implementer)
* If it is not an instance of a class or interface, declare
* or if the unwrapping conversion fails
* @throws NoSuchFieldException if a field with the specified name is not found
*/
public static void setField(Object invokeObject, String fieldName,
Object value) throws IllegalAccessException, NoSuchFieldException {
Field field = searchField(invokeObject, fieldName);
String className = field.getType().getName();
Object convObj = null;
if (field.getType().isInstance(value)) {
convObj = value;
} else {
convObj = convObject(value, className);
}
field.set(invokeObject, convObj);
}
/**
* Set the value of the field name "fieldName" of the execution object "invokeObject" to
* Get.
* @param invokeObject Object to be executed
* @param fieldName Field name of object to be executed
* @return return value
* @throws IllegalAccessException If the specified object is
* field (or its subclass or implementer)
* If it is not an instance of a class or interface, declare
* or if the unwrapping conversion fails
* @throws NoSuchFieldException if a field with the specified name is not found
*/
public static Object getField(Object invokeObject, String fieldName)
throws IllegalAccessException, NoSuchFieldException {
Field field = searchField(invokeObject, fieldName);
return field.get(invokeObject);
}
/**
* Check whether the object "object" declares the field name "fieldName"
* confirm.
* @param object Object to be inspected
* @param fieldName Field name to inspect
* @return true if declared
* @throws Exception
*/
public static boolean hasField(Object object, String fieldName)
throws Exception {
PropertyDescriptor[] props = getPropertyDescriptors(object);
for (int i = 0; i < props.length; i++) {
String _fieldName = props[i].getName();
if (fieldName.equals(_fieldName)) {
return true;
}
}
return false;
}
/**
*
* @param object
* @return
* @throws Exception
*/
public static TreeSet getAllFields(Object object) throws Exception {
TreeSet fieldSet = new TreeSet();
// Get property name from method
PropertyDescriptor[] props = getPropertyDescriptors(object);
for (int i = 0; i < props.length; i++) {
String fieldName = props[i].getName();
fieldSet.add(fieldName);
}
// Get property name from field
Field[] fields = object.getClass().getFields();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
if (!fieldSet.contains(fieldName)) {
fieldSet.add(fieldName);
}
}
return fieldSet;
}
/**
*
* @param invokeObject Object to be executed
* @param fieldName Field name of object to be executed
* @return Filed objects that match the specified argument conditions
* @throws NoSuchFieldException if a field with the specified name is not found
*/
private static Field searchField(Object invokeObject, String fieldName)
throws NoSuchFieldException {
try {
return invokeObject.getClass().getField(fieldName);
} catch (NoSuchFieldException e) {
// This scope is obtained from the table column name
fieldName = checkFieldName(fieldName);
Field[] fields = invokeObject.getClass().getFields();
for (int i = 0; i < fields.length; i++) {
if (fields[i].getName().equalsIgnoreCase(fieldName)) {
return fields[i];
}
}
throw new NoSuchFieldException(fieldName);
}
}
// ----------------------" others "
/**
* Get the unqualified class name from an object.
* @param object
* @return
*/
public static String getShortClassName(Object object) {
if (object == null) {
return “null”;
}
String name = object.getClass().getName();
return getShortClassName(name);
}
/**
* Get the class name from the fully qualified name.
* @param className
* @return
*/
public static String getShortClassName(String className) {
int index = className.lastIndexOf(“.”);
return className.substring(index + 1);
}
/**
* Change the field name from the method name. Conforms to JavaBeans conventions
* is needed.
* @param methodName
* @return
*/
public static String getFieldName(String methodName) {
String fieldName = null;
if (methodName.startsWith(“is”)) {
fieldName = methodName.substring(2);
} else {
fieldName = methodName.substring(3);
}
fieldName = convString(fieldName, 0, “L”);
return fieldName;
}
/**
* Verify that the fully qualified name "className" is an existing class name.
* @param className
* @return
*/
public static boolean isClassExist(String className) {
try {
Class.forName(className);
return true;
} catch (Exception e) {
return false;
}
}
private final static Map beanInfoCache = new HashMap();
/**
* Returns a PropertyDescriptor that holds object information for "object".
* @param object
* @return
* @throws IntrospectionException
*/
public static PropertyDescriptor[] getPropertyDescriptors(Object object)
throws IntrospectionException {
BeanInfo beanInfo = (BeanInfo) beanInfoCache.get(object.getClass());
if (beanInfo == null) {
beanInfo = Introspector.getBeanInfo(object.getClass());
beanInfoCache.put(object.getClass(), beanInfo);
}
// BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
return beanInfo.getPropertyDescriptors();
}
// ————————————————————————–
// ———————————————“Private method below”
// ————————————————————————–
/**
* Search for the accessor method for the argument fieldName based on PropertyDescriptor.
* @param invokeObject Object to be executed
* @param fieldName field name
* @param type Getter method ⇒ GET Getter method ⇒ SET
* @return Method object that matches the specified argument conditions
* @throws NoSuchMethodException If no matching method is found,
* Or if the name is “ " or " ”
* in the case of
* @throws IntrospectionException
*/
private static Method searchMethod(Object invokeObject, String fieldName,
String type) throws NoSuchMethodException, IntrospectionException {
Method method = null;
fieldName = checkFieldName(fieldName);
PropertyDescriptor[] props = getPropertyDescriptors(invokeObject);
for (int i = 0; i < props.length; i++) {
String name = props[i].getName();
if (!name.equalsIgnoreCase(fieldName)) {
continue;
}
if (type.equals(GET)) {
method = props[i].getReadMethod();
} else {
method = props[i].getWriteMethod();
}
if (method == null) {
continue;
}
return method;
}
// If the method does not exist.
throw new NoSuchMethodException(“Class has no methods.”
+ “(Case insensitive.): ” + type.toLowerCase()
+ convString(fieldName, 0, “U”) + “()”);
}
/**
* Checks if the argument fieldName is a column name; if it is a column name,
* Convert back.
*
* MAIL_ADDRESS ⇒ MAILADDRESS ↓ mailaddress = mailAddress
* @param fieldName field name or column name
* @return field name
*/
private static String checkFieldName(String fieldName) {
int index = fieldName.indexOf(“_”);
while (true) {
if (index == -1) {
return fieldName;
}
StringBuffer convcloumn = new StringBuffer(fieldName);
convcloumn.deleteCharAt(index);
fieldName = convcloumn.toString();
index = fieldName.indexOf(“_”);
}
}
/**
* Converts the object to be converted, object, to the type of convClassName.
*
* @param object Object to be converted
* @param convClassName class string of type to convert
* @return the converted object
*/
private static Object convObject(Object object, String convClassName) {
if (object == null) {
// Returning null when converting to a primitive type will result in an error.
// Make it a wrapper for 0.
if (convClassName.equals(“int”)) {
return new Integer(0);
} else if (convClassName.equals(“long”)) {
return new Long(0);
} else {
return null;
}
}
if (object.getClass().getName().equals(convClassName)) {
return object;
}
// —————————————-『object instanceof String』
if (object instanceof String) {
if (convClassName.equals(“java.lang.String”)) {
return object;
} else if (convClassName.equals(“java.lang.Long”)
|| convClassName.equals(“long”)) {
String str = (String) object;
if (isExist(str)) {
// It will be bad if you don't convert it to BigDecimal once
// 1000.00000
BigDecimal big = new BigDecimal(str);
return new Long(big.longValue());
} else {
// If str is a shell literal, set the initial value to “0”
return new Long(0);
}
} else if (convClassName.equals(“java.sql.Date”)) {
return toSqlDate((String) object);
} else if (convClassName.equals(“java.sql.Timestamp”)) {
Date date = toSqlDate((String) object);
return new Timestamp(date.getTime());
} else if (convClassName.equals(“java.lang.Integer”)
|| convClassName.equals(“int”)) {
// If str is a shell literal, set the initial value to “0”
String str = (String) object;
if (isExist(str)) {
BigDecimal big = new BigDecimal(str);
return new Integer(big.intValue());
} else {
return new Integer(0);
}
} else if (convClassName.equals(“boolean”)) {
return Boolean.valueOf(object.toString());
} else if (convClassName.equals(“java.math.BigDecimal”)) {
String temp = ((String) object).trim();
// If temp.length() == 0, it is safe to set it to null instead of 0.
if (temp.length() == 0) {
return null;
} else {
return new BigDecimal(temp);
}
}
throwNoSupprt(object, convClassName);
}
// ———————————“ object instanceof java.sql.Date ”
else if (object instanceof java.sql.Date) {
if (convClassName.equals(“java.lang.String”)) {
return toStringDate((java.sql.Date) object, “yyyy/MM/dd”);
} else if (convClassName.equals(“java.sql.Date”)) {
return object;
} else if (convClassName.equals(“java.sql.Timestamp”)) {
return new Timestamp(((Date) object).getTime());
}
throwNoSupprt(object, convClassName);
}
// ————————————-『object instanceof Timestamp』
else if (object instanceof Timestamp) {
long time = ((Timestamp) object).getTime();
if (convClassName.equals(“java.lang.String”)) {
return toStringDate(time, “yyyy/MM/dd HH:mm:ss”);
} else if (convClassName.equals(“java.sql.Date”)) {
return new java.sql.Date(time);
} else if (convClassName.equals(“java.sql.Timestamp”)) {
return object;
}
throwNoSupprt(object, convClassName);
}
// —————————————-『object instanceof Integer』
else if (object instanceof Integer) {
if (convClassName.equals(“java.lang.Integer”)
|| convClassName.equals(“int”)) {
return object;
} else if (convClassName.equals(“java.lang.String”)) {
return object.toString();
} else if (convClassName.equals(“java.lang.Long”)
|| convClassName.equals(“long”)) {
return new Long(((Integer) object).longValue());
} else if (convClassName.equals(“java.math.BigDecimal”)) {
return new BigDecimal(((Integer) object).intValue());
}
throwNoSupprt(object, convClassName);
}
// ——————————————『object instanceof Long』
else if (object instanceof Long) {
if (convClassName.equals(“java.lang.Long”)
|| convClassName.equals(“long”)) {
return object;
} else if (convClassName.equals(“java.lang.String”)) {
return object.toString();
} else if (convClassName.equals(“java.lang.Integer”)
|| convClassName.equals(“int”)) {
return new Integer(((Long) object).intValue());
} else if (convClassName.equals(“java.math.BigDecimal”)) {
return new BigDecimal(((Long) object).longValue());
}
throwNoSupprt(object, convClassName);
}
// —————————————-『object instanceof Double』
else if (object instanceof Double) {
if (convClassName.equals(“java.lang.String”)) {
// COLUMN NUMBER(8,0)
// windows oracle > BigDecimal
// UNIX oracle > Double
BigDecimal big = new BigDecimal(((Double) object).doubleValue());
int scale = big.scale();
if (scale == 0) {
return big.toString();
} else {
// Not supported if rounding is required.
throwNoSupprt(object, convClassName);
}
}
if (convClassName.equals(“java.lang.Integer”)
|| convClassName.equals(“int”)) {
return new Integer(((Double) object).intValue());
} else if (convClassName.equals(“java.lang.Long”)
|| convClassName.equals(“long”)) {
return new Long(((Double) object).longValue());
} else if (convClassName.equals(“java.math.BigDecimal”)) {
return new BigDecimal(((Double) object).doubleValue());
}
throwNoSupprt(object, convClassName);
}
// ————————————“ object instanceof BigDecimal ”
else if (object instanceof BigDecimal) {
if (convClassName.equals(“java.lang.String”)) {
return object.toString();
} else if (convClassName.equals(“java.lang.Long”)
|| convClassName.equals(“long”)) {
return new Long(((BigDecimal) object).longValue());
} else if (convClassName.equals(“java.lang.Integer”)
|| convClassName.equals(“int”)) {
return new Integer(((BigDecimal) object).intValue());
}
throwNoSupprt(object, convClassName);
}
// —————————————-『object instanceof byte[]』
else if (object instanceof byte[]) {
if (convClassName.equals(“java.sql.Blob”)) {
return object;
}
throwNoSupprt(object, convClassName);
}
// ————————————————“ object is Boolean”
else if (object instanceof Boolean) {
if (convClassName.equals(“boolean”)) {
return object;
}
throwNoSupprt(object, convClassName);
}
// ———————————————-『object is boolean[]』
else if (object instanceof boolean[]) {
if (convClassName.equals(“java.lang.String”)) {
boolean[] bs = (boolean[]) object;
StringBuffer buff = new StringBuffer(“[“);
for (int i = 0; i < bs.length; i++) {
buff.append(bs[i] + “,”);
}
buff.deleteCharAt(buff.length() – 1);
buff.append(“]”);
return buff.toString();
}
throwNoSupprt(object, convClassName);
}
throwNoSupprt(object, convClassName);
return null;
}
/**
*Throws if the conversion is not supported.
*
* @param object Object to be converted
* @param convClassName Type to convert
*/
private static void throwNoSupprt(Object object, String convClassName) {
String className = (object != null) ? object.getClass().getName()
: “null”;
String errorMess = “\nType conversion processing for this Object is not yet supported.\n”
+ ” [ Object ] = ” + object + “,[ Object type ] = ” + className
+ “,[ convertClass ] = ” + convClassName + “”;
throw new UnsupportedOperationException(errorMess);
}
/**
* Converts the character at position [index] of string [str] to uppercase or lowercase.
* <p>
* @param str String to be evaluated
* @param index Specified position
* @param toCase Convert to upper case ⇒ U | u Convert to lower case ⇒ L | l
* @return String after conversion
*/
private static String convString(String str, int index, String toCase) {
if (str == null || str.trim().length() == 0) {
return str;
} else {
String temp = str.substring(index, index + 1);
if (toCase.equalsIgnoreCase(“u”)) {
temp = temp.toUpperCase();
} else {
temp = temp.toLowerCase();
}
StringBuffer tempBuffer = new StringBuffer(str);
tempBuffer.replace(index, index + 1, temp);
return tempBuffer.toString();
}
}
/**
* Verify if [value] is a valid value.
*
* @param value String to be evaluated
* @return [true]: If not null and not “”
*/
private static boolean isExist(String value) {
if (value != null && value.length() != 0) {
return true;
}
return false;
}
/**
* java.util.Date class or its subclass in specified format
* Convert to string.
* @param date java.util.Date class to be converted
* @param pattern specified format
* @return formatted date string
*/
private static String toStringDate(Date date, String pattern) {
SimpleDateFormat sdFormat = new SimpleDateFormat(pattern);
return sdFormat.format(date);
}
private static java.sql.Date toSqlDate(String strDate) {
Calendar cal = toCalendar(strDate);
return toSqlDate(cal);
}
private static java.sql.Date toSqlDate(Calendar cal) {
long l = cal.getTime().getTime();
return new java.sql.Date(l);
}
/**
* Converts a long time value to a string in the specified format.
* @param time A long value representing milliseconds of the current time.
* @param pattern specified format
* @return formatted date string
*/
private static String toStringDate(long time, String pattern) {
return toStringDate(new Date(time), pattern);
}
/**
* String ⇒ java.sql.Date
*
* Convert the following date string to java.sql.Date
* yyyy/MM/dd HH:mm:ss.SSS yyyy-MM-dd HH:mm:ss.SSS
*
* “20030407” “2003/04/07” “2003-04-07” “2003/04/07 15:20:16” “2003-04-07
* 15:20:16”
* @param strDate
* @return
*/
private static Calendar toCalendar(String strDate) {
strDate = format(strDate);
Calendar cal = Calendar.getInstance();
int yyyy = Integer.parseInt(strDate.substring(0, 4));
int MM = Integer.parseInt(strDate.substring(5, 7));
int dd = Integer.parseInt(strDate.substring(8, 10));
int HH = cal.get(Calendar.HOUR_OF_DAY);
int mm = cal.get(Calendar.MINUTE);
int ss = cal.get(Calendar.SECOND);
int SSS = cal.get(Calendar.MILLISECOND);
cal.clear();
cal.set(yyyy, MM – 1, dd);
int len = strDate.length();
switch (len) {
case 10:
break;
case 16: // yyyy/MM/dd HH:mm
HH = Integer.parseInt(strDate.substring(11, 13));
mm = Integer.parseInt(strDate.substring(14, 16));
cal.set(Calendar.HOUR_OF_DAY, HH);
cal.set(Calendar.MINUTE, mm);
break;
case 19: // yyyy/MM/dd HH:mm:ss
HH = Integer.parseInt(strDate.substring(11, 13));
mm = Integer.parseInt(strDate.substring(14, 16));
ss = Integer.parseInt(strDate.substring(17, 19));
cal.set(Calendar.HOUR_OF_DAY, HH);
cal.set(Calendar.MINUTE, mm);
cal.set(Calendar.SECOND, ss);
break;
case 23: // yyyy/MM/dd HH:mm:ss.SSS
HH = Integer.parseInt(strDate.substring(11, 13));
mm = Integer.parseInt(strDate.substring(14, 16));
ss = Integer.parseInt(strDate.substring(17, 19));
SSS = Integer.parseInt(strDate.substring(20, 23));
cal.set(Calendar.HOUR_OF_DAY, HH);
cal.set(Calendar.MINUTE, mm);
cal.set(Calendar.SECOND, ss);
cal.set(Calendar.MILLISECOND, SSS);
break;
default:
throw new IllegalStateException(
“This String string cannot be converted to a date string: ”
+ strDate);
}
return cal;
}
/**
* Any date string as “yyyy/MM/dd” or “yyyy/MM/dd HH:mm:ss”
* Attempts to convert to format.
* Example: 03/1/3 ⇒ 2003/01/03
* @param strDate
* @return
*/
private static String format(String strDate) {
strDate = strDate.trim();
String yyyy = null;
String MM = null;
String dd = null;
String HH = null;
String mm = null;
String ss = null;
String SSS = null;
// If “-” or “/” is missing
if (strDate.indexOf(“/”) == -1 && strDate.indexOf(“-“) == -1) {
if (strDate.length() == 8) {
yyyy = strDate.substring(0, 4);
MM = strDate.substring(4, 6);
dd = strDate.substring(6, 8);
return yyyy + “/” + MM + “/” + dd;
} else {
yyyy = strDate.substring(0, 4);
MM = strDate.substring(4, 6);
dd = strDate.substring(6, 8);
HH = strDate.substring(9, 11);
mm = strDate.substring(12, 14);
ss = strDate.substring(15, 17);
return yyyy + “/” + MM + “/” + dd + ” ” + HH + “:” + mm + “:”
+ss;
}
}
StringTokenizer token = new StringTokenizer(strDate, “_/-:. “);
StringBuffer result = new StringBuffer();
for (int i = 0; token.hasMoreTokens(); i++) {
String temp = token.nextToken();
switch (i) {
case 0:// year part
yyyy = fillString(strDate, temp, “f”, “20”, 4);
result.append(yyyy);
break;
case 1:// month part
MM = fillString(strDate, temp, “f”, “0”, 2);
result.append(“/” + MM);
break;
case 2:// day part
dd = fillString(strDate, temp, “f”, “0”, 2);
result.append(“/” + dd);
break;
case 3:// time part
HH = fillString(strDate, temp, “f”, “0”, 2);
result.append(” ” + HH);
break;
case 4:// minute part
mm = fillString(strDate, temp, “f”, “0”, 2);
result.append(“:” + mm);
break;
case 5:// second part
ss = fillString(strDate, temp, “f”, “0”, 2);
result.append(“:” + ss);
break;
case 6:// millisecond part
SSS = fillString(strDate, temp, “b”, “0”, 3);
result.append(“.” + SSS);
break;
}
}
return result.toString();
}
private static String fillString(String strDate, String str,
String position, String addStr, int len) {
if (str.length() > len) {
String mes = strDate + “This String string cannot be converted to a date string”;
throw new IllegalStateException(mes);
}
return fillString(str, position, addStr, len);
}
/**
* Add the string [addStr] to be added to the string [str] at [position] in [len]
* Insert until full.
* <p>
* Example: String ss = StringUtil.fillString(“aaa”,”b”,”0″,7); ss ⇒ “aaa0000”
*
* *fillString() inserts until len is filled, but addString() inserts len.
*
* @param str target string
* @param position Insert before ⇒ F/f Insert after ⇒ B/b
* @param addStr String to insert
* @param len Number of digits to replenish
* @return The string after conversion. [str] is null or empty literal, [addStr] is set to [len]
* Returns inserted results until satisfied.
*/
private static String fillString(String str, String position,
String addStr, int len) {
StringBuffer tempBuffer = null;
if (!isExist(str)) {
tempBuffer = new StringBuffer();
for (int i = 0; i < len; i++) {
tempBuffer.append(addStr);
}
return tempBuffer.toString();
} else if (str.length() != len) {
tempBuffer = new StringBuffer(str);
while (len > tempBuffer.length()) {
if (position.equalsIgnoreCase(“f”)) {
tempBuffer.insert(0, addStr);
} else {
tempBuffer.append(addStr);
}
}
return tempBuffer.toString();
}
return str;
}
}