Wednesday, January 29, 2014

Getting Generic Types in Java

Due to some crazy inter-process communication, and serialization I needed to do I ended up with an interesting problem.  Now I will admit I was probably over complicating things, or doing something I didn't need to do, but I had a lot of fun writing this and learning about the internal workings of the JVM.

The problem, I needed to be able to check if a specific method of Class that implements my interface, if it's signature matches objects that I receive elsewhere.  Now I didn't want to just execute this method and throw an exception since it would occur at a later time.  I needed to check at the moment I get the parameters so I can give the user (probably more likely the programmer using my library) a reliable and easy to understand error message if it doesn't match.

After looking on stack overflow most posts that were looking to do the same thing the responses where you can't.  Now I'm not generally one to let things go and if someone says you can't I try to prove them wrong.  Well anyways here is some sample code that demonstraits how you can get this.  There are some catches and some special cases I actually handled in my code, but this should get the point across. It's by no means elegain and I would recommend you try to find better ways, but if you really need to do this, well here you go.

No comments:

Post a Comment