How to get Generic Metadata from a Class at Runtime

Like Annotations, Generics are also a runtime metadata that you can process at the run time.

Here you can see how to traverse the runtime information to get this information. You Can simply traverse the inheritance tree ofr the class and get the metadata of the generic definition. Somthing like

 public static Type[] getGenericDefinitons(Class classFrom, Class class1) ;
Type[] types=getGenericDefinitons(MockClass1.class,GenericInterface.class);//[String.class,Long.class,Integer.class] expected

First The Sample Cases :


public interface GenericInterface <T,K,L>{}

 public interface MockClass1 extends GenericInterface<String,Long,Integer>{}
 public interface MockClass11<T,K,L> extends GenericInterface<T,K,L>{}
 public interface MockClass12 extends MockClass11<String,Long,Integer>{}
 public interface MockClass2 extends MockClass1{}

 public class MockClass3 implements GenericInterface<String,Long,Integer>{}
 public class MockClass4 extends MockClass3{}

 public class GenericClass <T,K,L>{}
 public class AMockClass2 extends AMockClass1{}
 public class AMockClass1 extends GenericClass<String,Long,Integer>{}

And the java class metadata traverser to retrieve the Generic Information


public class Utils {

 /**Get the Generic definition from a class for given class with given index
 * @param clz Implementing class
 * @param class1 class with generic definition
 * @param index generic index
 *  @return null if not found
 * */

 public static Type getGenericDefiniton( Class clz, Class class1, int index) {
 Type[] t = getGenericDefinitons(clz, class1);
 if (t != null && t.length > index)
 return t[index];
 return null;

 }
 /**Get the Generic definitions from a class for given class
 * @param clz Implementing class
 * @param class1 class with generic definition
 * @return null if not found
 * */
 public static Type[] getGenericDefinitons(Class clz, Class class1) {
 Type[] t = null;
 while (clz != null) {

 t = getGenericDefinitonsThis(clz, class1);
 if (t != null)
 return t;
 Class[] interfaces = clz.getInterfaces();
 for (Class class2 : interfaces) {
 t = getGenericDefinitonsThis(class2, class1);
 if (t != null)
 return t;
 }
 clz = clz.getSuperclass();
 }
 return t;
 }
 /**Get the Generic definitions from a class for given class without looking super classes
 * @param clz Implementing class
 * @param class1 class with generic definition
 * @return null if not found
 * */
 public static Type[] getGenericDefinitonsThis(Class classFrom, Class class1) {

 Type[] genericInterfaces = classFrom.getGenericInterfaces();
 for (Type type : genericInterfaces) {
 if (type instanceof ParameterizedType) {
 ParameterizedType pt = (ParameterizedType) type;

 if (class1.isAssignableFrom((Class) pt.getRawType())) {
 Type[] actualTypeArguments = pt.getActualTypeArguments();
 return actualTypeArguments;
 }
 }

 }
 // check if it if available on generic super class
 Type genericSuperclass = classFrom.getGenericSuperclass();
 if (genericSuperclass instanceof ParameterizedType) {
 ParameterizedType pt = (ParameterizedType) genericSuperclass;

 if (class1.equals(pt.getRawType())) {
 Type[] actualTypeArguments = pt.getActualTypeArguments();
 return actualTypeArguments;
 }
 }
 return null;

 }

}

And the test case

PS: This class is not tested for Multi-dimensional Generic Definitions


public class UtilsTest {
 @Test
 public void simpleInterfaceExtend(){
 Type[] genericDefinitons = Utils.getGenericDefinitons(MockClass1.class, GenericInterface.class);
 compareResults(genericDefinitons);
 }

 @Test
 public void simpleInterfaceExtend2(){

 Type[] genericDefinitons = Utils.getGenericDefinitons(MockClass2.class, GenericInterface.class);
 compareResults(genericDefinitons);
 }
 @Test
 public void simpleInterfaceExtend3(){

 Type[] genericDefinitons = Utils.getGenericDefinitons(MockClass12.class, GenericInterface.class);
 compareResults(genericDefinitons);
 }
 @Test
 public void simpleInterfaceImplements(){
 Type[] genericDefinitons = Utils.getGenericDefinitons(MockClass3.class, GenericInterface.class);
 compareResults(genericDefinitons);
 }
 @Test
 public void simpleInterfaceImplements2(){

 Type[] genericDefinitons = Utils.getGenericDefinitons(MockClass4.class, GenericInterface.class);
 compareResults(genericDefinitons);
 }

 @Test
 public void simpleClassImplements(){
 Type[] genericDefinitons = Utils.getGenericDefinitons(AMockClass1.class, GenericClass.class);
 compareResults(genericDefinitons);
 }
 @Test
 public void simpleClassImplements2(){

 Type[] genericDefinitons = Utils.getGenericDefinitons(AMockClass2.class, GenericClass.class);
 compareResults(genericDefinitons);
 }

 private void compareResults(Type[] genericDefinitons) {
 assertEquals(String.class,genericDefinitons[0]);
 assertEquals(Long.class,genericDefinitons[1]);
 assertEquals(Integer.class,genericDefinitons[2]);
 }

}

Ruby on Rails experience of a java developer

Ruby on Rails logo

Image via Wikipedia

Although it has not been a long time since I started to develop a small rails application, I would like to share notes.

the first point ,for me and for all the Java developers like me, should be: “what kind of language is this  ???” :) yes it is not  structured and well defined like Java , there are lots of tricks going around.  Even the simple for loops seems complex.

and for such a tricky language you cannot expect to find a full-functional CTRL-SPACE support. and for me it is still a pain.

To save yourself from any more pain I would suggest you to setup your environment with instantRails and aptana radrails.

however after you get used to this alien language, you would start to enjoy it. that is what started to do.  I really understood the real meaning of light-weight and agile. Although I do feel myself as secure and powerful as in Java, I still enjoyed it.

what was missing grails?

almost a year ago I tried grails also, I have seen some sparkles in it but that wasn’t the tool I have been looking for. it was not agile, the development cycle is painful. it was a pre-configured spring-hibernate setup with groovy.

the pain of grails does come from its power actually, spring-hibernate. it is really HEAVY.

The Sparkles

I don’t have too much experience, but I can easily say, development with it is way faster than Java or grails and way powerful than PHP.if you are looking for easy way to develop a web site that is the language you should look first.  It has  good and simple web-life cycle and built in support for web standard like json,xml and ajax.

The Volcano: Java

Although rails has good point it is not as powerful as java, and it is not complete alternative to java either.(don’t hesitate  to post your comments). So for the moment I am searching for integration strategies.

Enhanced by Zemanta

Executors.newFixedThreadPool(n) – Suspended Threads

Only Exception is Real

Image by valentin.d via Flickr

Yesterday while I am trying to organize threads in Java I noticed something strange !!

Simply the default ExecutorService  could not manage to recover suspended threads.

After a small investigation, it looks like if any of the running thread throws any RuntimeException, ExecutorService may not recover and could not start any waiting runnable.

You can check the java code below.

SmartFix: Don’t throw any exception :P

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorsTest {

	private static ExecutorService executorService;

	public static void main(String[] args) {
	    executorService = Executors.newFixedThreadPool(10);
	    for (int i = 0; i < 10000; i++) {
	        executorService.execute(new MyRunnable());
        }
    }

	public static class MyRunnable implements Runnable{

		@Override
        public void run() {
			while(true){
				long t=(long) (Math.random()*1000*10);
				try {
	                Thread.sleep(t);
                } catch (InterruptedException e) {}
                if(t<3000){
                	System.out.println(Thread.activeCount());
                	// COMMENT AND UNCOMMENT THE LINE BELOW TO SEE THE DIFFERENCE
                	throw new RuntimeException("s");

                }
			}
        }
	}
}
Enhanced by Zemanta

Focus on:Refactoring

My desk is a little untidy at the moment

Image by Neil Crosby via Flickr

Seperation of Concepts
Inversion Of Control
Desing patterns

They are all trying to tell you one common thing.

Please Make It Simple  and Organized

No matter what size is your project and how many teams/developers involved, the complexity if the code has tendency to be more complex. And after awhile it turn in to a YET another OLD piece of CRAP.

Refactoring is the only way to avoid this fate. Here is some tools and practices that would help you

Enhanced by Zemanta

On track again

On the right track - White Rock

Image by janusz l via Flickr

After a silent year , it is good to be back on bloging again :)

Enhanced by Zemanta

Just show me what you have done

Mount Erciyes
Image via Wikipedia

Software development is one of the mysterious processes for the people who know little or  nothing about the process.

But when talking about the quality, it is not the colors or the make up of the screens you should be talking. (I am not under estimating how important it is, but I am talking about machine not the color of the box).

there are lots of people there talking about their AMAZING success stories.

I proudly present the ultimate tool that would change your life

I am sure they have done amazing performance numbers with help some hardware and some good practices. They are really happy to create the little mountains (Turkish idiom).  Let’s ask them: Read more

it (doesn’t) worth it

The Golden Age by Lucas Cranach the Elder.
Image via Wikipedia

When I graduated from college I was really dreaming software companies as the utopia companies. They should be different then any other sector or firm. They are full of highly graduated people with lots of ideas and future projects. It took not much time too see the truth.

Software Companies are full of upset people !!!! Read more