001/** 002 * GRANITE DATA SERVICES 003 * Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S. 004 * 005 * This file is part of the Granite Data Services Platform. 006 * 007 * Granite Data Services is free software; you can redistribute it and/or 008 * modify it under the terms of the GNU Lesser General Public 009 * License as published by the Free Software Foundation; either 010 * version 2.1 of the License, or (at your option) any later version. 011 * 012 * Granite Data Services is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 015 * General Public License for more details. 016 * 017 * You should have received a copy of the GNU Lesser General Public 018 * License along with this library; if not, write to the Free Software 019 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 020 * USA, or see <http://www.gnu.org/licenses/>. 021 */ 022package org.granite.messaging.amf.io.convert; 023 024import java.lang.reflect.Type; 025import java.lang.reflect.TypeVariable; 026 027import org.granite.util.TypeUtil; 028 029/** 030 * @author Franck WOLFF 031 */ 032public abstract class Converter { 033 034 protected final Converters converters; 035 036 /** 037 * Build a new Converter instance. 038 * 039 * @param converters a {@link Converters} instance (must be not null). 040 * @throws NullPointerException (if converters is null). 041 */ 042 public Converter(Converters converters) { 043 if (converters == null) 044 throw new NullPointerException("converters parameter cannot be null"); 045 this.converters = converters; 046 } 047 048 /** 049 * Tells if the supplied object may be converted to the supplied target type by 050 * this converter. 051 * 052 * @param value the object to be converted. 053 * @param targetType the target type. 054 * @return true if this converter can convert o to the target type, false otherwise. 055 */ 056 public final boolean canConvert(Object value, Type targetType) { 057 if (targetType instanceof TypeVariable<?>) 058 targetType = TypeUtil.getBoundType((TypeVariable<?>)targetType); 059 return internalCanConvert(value, targetType); 060 } 061 062 protected abstract boolean internalCanConvert(Object value, Type targetType); 063 064 /** 065 * Converts the supplied object to the supplied target type. 066 * 067 * @param value the object to be converted. 068 * @param targetType the target type. 069 * @return the converted object. 070 */ 071 public final Object convert(Object value, Type targetType) { 072 if (targetType instanceof TypeVariable<?>) 073 targetType = TypeUtil.getBoundType((TypeVariable<?>)targetType); 074 return internalConvert(value, targetType); 075 } 076 077 protected abstract Object internalConvert(Object value, Type targetType); 078}