001package ball.util.ant.types;
002/*-
003 * ##########################################################################
004 * Utilities
005 * $Id: TypedAttributeType.java 5285 2020-02-05 04:23:21Z ball $
006 * $HeadURL: svn+ssh://svn.hcf.dev/var/spool/scm/repository.svn/ball-util/trunk/src/main/java/ball/util/ant/types/TypedAttributeType.java $
007 * %%
008 * Copyright (C) 2008 - 2020 Allen D. Ball
009 * %%
010 * Licensed under the Apache License, Version 2.0 (the "License");
011 * you may not use this file except in compliance with the License.
012 * You may obtain a copy of the License at
013 *
014 *      http://www.apache.org/licenses/LICENSE-2.0
015 *
016 * Unless required by applicable law or agreed to in writing, software
017 * distributed under the License is distributed on an "AS IS" BASIS,
018 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
019 * See the License for the specific language governing permissions and
020 * limitations under the License.
021 * ##########################################################################
022 */
023import ball.util.Factory;
024import ball.util.ant.taskdefs.NotNull;
025import java.beans.ConstructorProperties;
026import org.apache.tools.ant.BuildException;
027
028/**
029 * Class to provide a typed name-value (attribute) for
030 * {@link.uri http://ant.apache.org/ Ant} {@link org.apache.tools.ant.Task}
031 * implementations.
032 *
033 * {@bean.info}
034 *
035 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
036 * @version $Revision: 5285 $
037 */
038public class TypedAttributeType extends StringAttributeType {
039    private String type = String.class.getName();
040
041    /**
042     * @param   name            The attribute name.
043     */
044    @ConstructorProperties({ "name" })
045    public TypedAttributeType(String name) { super(name); }
046
047    /**
048     * No-argument constructor.
049     */
050    public TypedAttributeType() { this(null); }
051
052    @NotNull
053    public String getType() { return type; }
054    public void setType(String type) { this.type = type; }
055
056    public Object getTypedValue() throws BuildException {
057        return getTypedValue(getClass().getClassLoader());
058    }
059
060    public Object getTypedValue(ClassLoader loader) throws BuildException {
061        Object object = null;
062
063        try {
064            Class<?> type = Class.forName(getType(), false, loader);
065            Factory<?> factory = new Factory<>(type);
066
067            object = factory.getInstance(getValue());
068        } catch (BuildException exception) {
069            throw exception;
070        } catch (RuntimeException exception) {
071            throw exception;
072        } catch (Exception exception) {
073            throw new BuildException(exception);
074        }
075
076        return object;
077    }
078}