001/* -*- mode: Java; c-basic-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*- 002 * 003 * Copyright © 2020 microBean™. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://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 014 * implied. See the License for the specific language governing 015 * permissions and limitations under the License. 016 */ 017package org.microbean.settings.converter; 018 019import javax.enterprise.context.ApplicationScoped; 020import javax.enterprise.context.Dependent; 021 022import org.microbean.settings.Converter; 023import org.microbean.settings.Value; 024 025@Dependent 026public class ClassConverter<T> implements Converter<Class<T>> { 027 028 private static final long serialVersionUID = 1L; 029 030 public ClassConverter() { 031 super(); 032 } 033 034 @Override 035 public Class<T> convert(final Value value) { 036 final Class<T> returnValue; 037 if (value == null) { 038 returnValue = null; 039 } else { 040 final String className = value.get(); 041 if (className == null) { 042 returnValue = null; 043 } else { 044 Class<T> result = null; 045 try { 046 @SuppressWarnings("unchecked") 047 final Class<T> temp = (Class<T>)Class.forName(className, true, Thread.currentThread().getContextClassLoader()); 048 result = temp; 049 } catch (final ClassNotFoundException classNotFoundException) { 050 throw new IllegalArgumentException(className, classNotFoundException); 051 } finally { 052 returnValue = result; 053 } 054 } 055 } 056 return returnValue; 057 } 058 059}