Using Reflection API in liferay

Liferay provides an API to call any methods using Reflection.

First of all why do we use reflection API to call any method. In terms of liferay, liferay loads the classes from different scopes like application scope, portal scope, portlet scope etc. There are some classes which is in portal-impl.jar file and we can not use that classes directly in our application because this jar file is in portal scope and loaded by portal class loader. eg. LoginUtil methods.

Those methods can be used using PortalClassInvoker class. To invoke any method on the object of the Class, which is in the portal-impl.jar file, we need to create the method key. MethodKey is nothing but a key to identify the method in the class. The MethodKey has some constructor parameters like below.


public MethodKey(java.lang.Class declaringClass, java.lang.String methodName, java.lang.Class... parameterTypes);

The first parameter is the class object of the class which you want to invoke. second parameter is the method name, the last parameter is the array of class type where we can pass the comma saperated class type values for method parameters. ClassResolverUtil class playes the important role to find the class from any scope. if your class is in portal scope then use resolveByPortalClassLoader method to locate the class. The last thing is the PortalClassInvoker class to invoke the method. the parameter of the method is given below.


public static java.lang.Object invoke(boolean newInstance, com.liferay.portal.kernel.util.MethodKey methodKey, java.lang.Object... arguments) throws java.lang.Exception;

Finally we are ready to call the LoginUtil method in our portlet. the source code given below is the sample code for invoking getAuthenticatedUserId method on LoginUtil class.


MethodKey methodKey = new MethodKey(ClassResolverUtil.resolveByPortalClassLoader("com.liferay.portlet.login.util.LoginUtil"), "getAuthenticatedUserId", HttpServletRequest.class, String.class, String.class, String.class);
try {
long userId = GetterUtil.getLong(PortalClassInvoker.invoke(false, methodKey, request, "test@liferay.com", "test", null));
System.out.println("userId:"+ userId);
} catch (Exception e) {
//e.printStackTrace();
System.out.println("userId: exception thrown" + e );


}

Thanks Enjoy

Blogs