Posts Tagged ‘ dynamic ’

Dynamically Accessing Class Members using String Class Name in JAVA

Following is the code for dynamically accessing member of a class when class name is not availaible while compiling.
You can use this method to invoke the method of class whose class name is available in string. and whose member name is also available in string.

/**
	 * Method used for dynamically accessing values from a class object in java. on passing method name or variable name along with object.
	 * @param obj : The object whose member variable or method has to be called.
	 * @param methodName : the method name of obj to be called. (null if not required)
	 * @param varName :  the variable name of obj to be called. (null if not required)
	 * @return object or null
	 */
	public static Object getValues(Object obj, String methodName, String varName) {
		try {
			// Creating the class object
			Class myclass = Class.forName(obj.getClass().getSimpleName());
			if (null != methodName) {
				//Loading all the methods of class.
				Method[] methods = myclass.getMethods();
				for (int i = 0; i < methods.length; i++) {
					//searching for the method we required
					if (methods[i].getName().equals(methodName)) {
						//Invoking and returning the method we require over object we pass.
						return methods[i].invoke(obj);
					}
				}
			}
			if (null != varName) {
				//Loading all the fields of class
				Field[] fields = myclass.getFields();
				for (int i = 0; i < fields.length; i++) {
					//Searching for the field name we require
					if (fields[i].getName().equals(varName)) {
						//returning the value of the required field.
						return fields[i].get(obj);
					}

				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
Advertisements