Package net.sourceforge.javautil.common.coersion.impl

Source Code of net.sourceforge.javautil.common.coersion.impl.CoersionURL

package net.sourceforge.javautil.common.coersion.impl;

import java.net.MalformedURLException;
import java.net.URL;

import net.sourceforge.javautil.common.coersion.CoersionException;
import net.sourceforge.javautil.common.exception.ThrowableManagerRegistry;

/**
* This helps coerce a {@link String} into a {@link URL} and back.
*
* @author elponderador
* @author $Author$
* @version $Id$
*/
public class CoersionURL extends CoersionAbstract<String, URL> {

  public CoersionURL() {
    super(String.class, URL.class);
  }

  public Object coerce(Object original, Class target) {
    if (URL.class.isAssignableFrom(target)) {
      try {
        String url = (String) original;
        return url.contains(":/") ? new URL(url) : Thread.currentThread().getContextClassLoader().getResource(url);
      } catch (MalformedURLException e) {
        throw ThrowableManagerRegistry.caught(e);
      }
    } else if (original instanceof URL) {
      return ((URL)original).toExternalForm();
    }

    throw new CoersionException("Could not coerce: " + original + " into a " + target);
  }

}
TOP

Related Classes of net.sourceforge.javautil.common.coersion.impl.CoersionURL

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.