001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * https://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.beanutils.converters; 018 019import java.io.File; 020 021/** 022 * {@link org.apache.commons.beanutils.Converter} implementation that handles conversion 023 * to and from <strong>java.io.File</strong> objects. 024 * <p> 025 * Can be configured to either return a <em>default value</em> or throw a 026 * <code>ConversionException</code> if a conversion error occurs. 027 * 028 * @since 1.6 029 */ 030public final class FileConverter extends AbstractConverter { 031 032 /** 033 * Construct a <strong>java.io.File</strong> <em>Converter</em> that throws 034 * a <code>ConversionException</code> if an error occurs. 035 */ 036 public FileConverter() { 037 } 038 039 /** 040 * Construct a <strong>java.io.File</strong> <em>Converter</em> that returns 041 * a default value if an error occurs. 042 * 043 * @param defaultValue The default value to be returned 044 * if the value to be converted is missing or an error 045 * occurs converting the value. 046 */ 047 public FileConverter(final Object defaultValue) { 048 super(defaultValue); 049 } 050 051 /** 052 * <p>Convert the input object into a java.io.File.</p> 053 * 054 * @param <T> The target type of the conversion. 055 * @param type Data type to which this value should be converted. 056 * @param value The input value to be converted. 057 * @return The converted value. 058 * @throws Throwable if an error occurs converting to the specified type 059 * @since 1.8.0 060 */ 061 @Override 062 protected <T> T convertToType(final Class<T> type, final Object value) throws Throwable { 063 if (File.class.equals(type)) { 064 return type.cast(new File(value.toString())); 065 } 066 067 throw conversionException(type, value); 068 } 069 070 /** 071 * Return the default type this <code>Converter</code> handles. 072 * 073 * @return The default type this <code>Converter</code> handles. 074 * @since 1.8.0 075 */ 076 @Override 077 protected Class<?> getDefaultType() { 078 return File.class; 079 } 080}