001/* 002 * Copyright 2023 the original author or authors. 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package de.cuioss.test.valueobjects.generator.dynamic.impl; 017 018import java.lang.reflect.InvocationHandler; 019import java.util.Optional; 020 021import de.cuioss.test.generator.TypedGenerator; 022import de.cuioss.tools.reflect.MoreReflection; 023import lombok.AccessLevel; 024import lombok.RequiredArgsConstructor; 025 026/** 027 * Creates proxies for given interfaces, should only be used as last line of 028 * defense. 029 * 030 * @author Oliver Wolff 031 * @param <T> the type of objects to be generated 032 */ 033@RequiredArgsConstructor(access = AccessLevel.PRIVATE) 034public class InterfaceProxyGenerator<T> implements TypedGenerator<T> { 035 036 private static final InvocationHandler DEFAULT_HANDLER = new DefaultInvocationHandler(); 037 038 private final Class<T> type; 039 040 @Override 041 public T next() { 042 return MoreReflection.newProxy(type, DEFAULT_HANDLER); 043 } 044 045 @Override 046 public Class<T> getType() { 047 return type; 048 } 049 050 /** 051 * Factory method for creating an instance of {@link InterfaceProxyGenerator}. 052 * It only works with interfaces. 053 * 054 * @param type to be checked, should be an interface 055 * @return an {@link Optional} on the corresponding {@link TypedGenerator} if 056 * the given type is an interfaces, otherwise {@link Optional#empty()} 057 */ 058 public static final <T> Optional<TypedGenerator<T>> getGeneratorForType(final Class<T> type) { 059 if (null == type || type.isAnnotation() || !type.isInterface()) { 060 return Optional.empty(); 061 } 062 return Optional.of(new InterfaceProxyGenerator<>(type)); 063 } 064}