Tuesday, June 30, 2015

Invoke custom portlet service using Java Reflection


Requirement:
Create a custom service 'myPojo' in a custom portlet named 'my-portlet'.
Access the above service in a Liferay jsp via hook.
This can be achieved by placing the service jar in the tomcat-lib but in certain scenarios where the access and deployment restrictions are applied and deployment does not allow to manually deploy the service jar to tomcat-lib below approach will be helpful.

Portlet name : my-portlet
Service Entity : MyPojo
Method to invoke: getMyPojo
Pojo property to read : _myField (exact name can be verified from the service generated model implementation class MyPojoModelImpl)




ClassLoader classLoader = PortletBeanLocatorUtil.getBeanLocator("my-portlet").getClassLoader();
Class clazz = classLoader.loadClass("com.informatick.hub.service.MyPojoLocalServiceUtil");
java.lang.reflect.Method method = clazz.getMethod("getMyPojo", long.class);
Object retunedObject = method.invoke(clazz.newInstance(), classPK);
    
java.lang.reflect.Field ouaField;
Class beanClass = retunedObject.getClass().getSuperclass().getSuperclass();
        
 ouaField = beanClass.getDeclaredField("_myField");
 ouaField.setAccessible(true);
 String tempString = (String) ouaField.get(retunedObject);

 long oua = 0;
 oua = GetterUtil.getLong(tempString);

 System.out.println("Returned vvalue : "+oua)