Ever since I first got started programming and was exposed to different computer languages I've been annoyed at how difficult it is to convert information from one type to another. Not only does every language have its own way of doing this, often even within the same language there are multiple different methods that need to be learned to do conversions properly. I can't offer a solution for every programming language, but I can offer a solution for Java: the Morph framework. The main goal of Morph is to make it really easy to take information in one format and make it available in another format. I am including some examples along with this article to show how easy it is to do all sorts of conversions with Morph. You can get a full list of the conversions that come out of the box here.
Morph.convert allows you to convert an object from one type to another. Here are some examples:
Integer three = new Integer(3); // code without Morph String string = new Integer(three); // or (without using Morph) string = "" + three; // code using Morph String string = Morph.convertToString(three);
String three = "3"; // code without Morph Integer integer = new Integer(three); // code using Morph Integer integer = Morph.convertToIntegerObject(three);
String three = "3"; // code without Morph int i= new Integer(three).intValue(); // or (without using Morph) int i = Integer.parseInt(3); // code using Morph int i = Morph.convertToInt(three);
Morph.copy allows information from one object to be copied to another object. The object to which information is copied may even be of a different type than the source object. A great example of when you need to do this type of thing is when you need the data in an HttpServletRequest to be available to lower tiers in your application but you don't want to tie your entire application to the servlet API. For example, let's say you are trying to get your data prepared for a method with a signature IServiceInterface.service(Map data):
// without Morph Map data = new HashMap(); for (Enumeration e=request.getParameterNames(); e.hasNext(); ) { String param = (String) e.next(); data.put(param, request.getParameter(param)); } // with Morph Map data = new HashMap(); Morph.copy(data, request); // actually with this particular example could also do Map data = (Map) Morph.convert(Map.class, request);
Experience Spider Impact for Free
Schedule a live demo or claim your free 30-day trial. We’re standing by to either show off Spider Impact or turn your data into a prototype for free.