I need to use reflection with generic params. Here is an example class and test class of what I am trying to do. Running the test, I am getting error:
[ERROR : Method not found exception] : Method name 'EST2GMT'
Here is my reflect class with generic;
/*
* File: MyTransformer.java
* Created: Jul 22, 2014
*/
package company.online.project.my.transform;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import org.apache.log4j.Logger;
public class MyTransformer< T >
{
Logger LOG = Logger.getLogger( MyTransformer.class );
public T tranform( String functionName, T arg )
{
try
{
Method method = this.getClass().getDeclaredMethod( functionName, arg.getClass() );
return (T) method.invoke( this, arg );
}
catch ( NoSuchMethodException e )
{
System.out.println( "[ERROR : Method not found exception] : Method name '" + functionName + "'" );
}
catch ( java.lang.IllegalAccessException e )
{
System.out.println( "[ERROR : Illegal Access exception] : " + e.getMessage() );
}
catch ( java.lang.reflect.InvocationTargetException e )
{
System.out.println( "[ERROR : Invocation Target not found exception] : " + e.getMessage() );
}
return null;
}
public Date convert2Date( String date )
{
LOG.debug( "convert2Date function called" );
return new Date();
}
public Calendar EST2GMT( Calendar estTime )
{
LOG.debug( "EST2GMT function called :" + estTime.getTime().toString() );
return new GregorianCalendar( 2013, 0, 31 );
}
public String createcompanyKeys( List<T> values )
{
LOG.debug( "EST2GMT function called" );
return "String";
}
}
Here is my test class :
package company.online.project.my.transform;
import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class MyTransformerTest
{
MyTransformer transformer;
@Before
public void setUp()
{
transformer = new MyTransformer();
}
@Test
public void testGetMethod() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException
{
Calendar calendar = new GregorianCalendar( 2013, 0, 31 );
Assert.assertEquals( Calendar.class, transformer.tranform( "EST2GMT", calendar.getClass() );
}
}