当前位置: 首页>>代码示例>>Java>>正文


Java Constructor.getAnnotation方法代码示例

本文整理汇总了Java中java.lang.reflect.Constructor.getAnnotation方法的典型用法代码示例。如果您正苦于以下问题:Java Constructor.getAnnotation方法的具体用法?Java Constructor.getAnnotation怎么用?Java Constructor.getAnnotation使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.lang.reflect.Constructor的用法示例。


在下文中一共展示了Constructor.getAnnotation方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: init

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
public static void init(Object object) throws IllegalAccessException, InvocationTargetException, InstantiationException {
    if (object instanceof User) {
        Class clz = object.getClass();
        Constructor [] constructors = clz.getConstructors();
        for (Constructor constructor : constructors) {
            if (constructor.isAnnotationPresent(AConstructor.class)) {
                AConstructor aConstructor = (AConstructor) constructor.getAnnotation(AConstructor.class);
                String name = aConstructor.initName();
                int age = aConstructor.initAge();
                ((User) object).name = name;
                ((User) object).age = age;
            }
        }
    }else{
        throw new RuntimeException("无法向下转型到指定类");
    }

}
 
开发者ID:byhieg,项目名称:JavaTutorial,代码行数:19,代码来源:AConstructorProcess.java

示例2: getCreatorConstructor

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
public static Constructor<?> getCreatorConstructor(Class<?> clazz) {
    Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
    int length = declaredConstructors.length;
    int i = 0;
    while (i < length) {
        Constructor<?> constructor = declaredConstructors[i];
        if (((JSONCreator) constructor.getAnnotation(JSONCreator.class)) == null) {
            i++;
        } else if (null == null) {
            return constructor;
        } else {
            throw new JSONException("multi-json creator");
        }
    }
    return null;
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:17,代码来源:DeserializeBeanInfo.java

示例3: getCreatorConstructor

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
public static Constructor<?> getCreatorConstructor(Class<?> clazz) {
    Constructor<?> creatorConstructor = null;

    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
        JSONCreator annotation = constructor.getAnnotation(JSONCreator.class);
        if (annotation != null) {
            if (creatorConstructor != null) {
                throw new JSONException("multi-json creator");
            }

            creatorConstructor = constructor;
            break;
        }
    }
    return creatorConstructor;
}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:17,代码来源:DeserializeBeanInfo.java

示例4: parseConstructAnnotation

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
   * 简单打印出UserAnnotation 类中所使用到的构造方法注解
   * 该方法只打印了 构造方法 类型的注解
   * @throws ClassNotFoundException
   */
  @SuppressWarnings("rawtypes")
  public static void parseConstructAnnotation()  throws ClassNotFoundException{
Constructor[] constructors = UserAnnotation.class.getConstructors();
      for (Constructor constructor : constructors) {
          /* 
           * 判断构造方法中是否有指定注解类型的注解 
           */  
          boolean hasAnnotation = constructor.isAnnotationPresent(TestA.class);
          if(hasAnnotation){
               /* 
               * 根据注解类型返回方法的指定类型注解 
               */
              @SuppressWarnings("unchecked")
		TestA annotation = (TestA) constructor.getAnnotation(TestA.class);
              System.out.println("constructor = " + constructor.getName()  
                      + "   |   id = " + annotation.id() + "  |  description = "  
                      + annotation.name() + "  |   gid= "+annotation.gid());
          }
      }
  }
 
开发者ID:MinsxCloud,项目名称:minsx-java-example,代码行数:26,代码来源:ParseAnnotation.java

示例5: _getConstructorMapForTarget

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
private Map<Class<?>, Constructor> _getConstructorMapForTarget(Class<?> targetType)
{
  Map<Class<?>, Constructor> cachedConstructors = _cache.get(targetType);
  
  if (cachedConstructors == null)
  {
    cachedConstructors = _EMPTY_CONSTRUCTOR_MAP;      
    
    Constructor constructors[] = targetType.getConstructors();
    for (Constructor c:constructors)
    {
      // Use only public non-depricated constructors
      if (Modifier.isPublic(c.getModifiers()) && c.getAnnotation(Deprecated.class) == null)
      {
        Class<?> params[] = c.getParameterTypes();
        
        // We are looking for all single-parameter constructors
        if (params.length ==1)
        {
          if (cachedConstructors == _EMPTY_CONSTRUCTOR_MAP)
            cachedConstructors = new HashMap<Class<?>, Constructor>();
          
          cachedConstructors.put(params[0], c);
        }
      }
    }
    
    _cache.put(targetType, cachedConstructors);
  }
  return cachedConstructors;
}
 
开发者ID:apache,项目名称:myfaces-trinidad,代码行数:32,代码来源:ReflectionConverter.java

示例6: evaluate

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
public static String[] evaluate(Constructor<?> candidate, int paramCount) {
	ConstructorProperties cp = candidate.getAnnotation(ConstructorProperties.class);
	if (cp != null) {
		String[] names = cp.value();
		if (names.length != paramCount) {
			throw new IllegalStateException("Constructor annotated with @ConstructorProperties but not " +
					"corresponding to actual number of parameters (" + paramCount + "): " + candidate);
		}
		return names;
	}
	else {
		return null;
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:15,代码来源:ConstructorResolver.java

示例7: getConstructor

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
private Constructor<? extends Exception> getConstructor(Class<? extends Exception> exceptionClass) {
    Constructor<? extends Exception> preferredConstructor = null;
    for(Constructor<?> constructor : exceptionClass.getConstructors()) {

        FeignExceptionConstructor exceptionConstructor = constructor.getAnnotation(FeignExceptionConstructor.class);
        if(exceptionConstructor == null) {
            continue;
        }
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if(parameterTypes.length==0) {
            continue;
        }
        if(preferredConstructor == null) {
            preferredConstructor = (Constructor<? extends Exception>) constructor;
        }
        else {
            throw new IllegalStateException("Too many constructors marked with @FeignExceptionConstructor");
        }
    }

    if(preferredConstructor == null) {
        try {
            return exceptionClass.getConstructor();
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException(
                "Cannot find any suitable constructor in class [" + exceptionClass.getName() + "] - did you forget to mark one with @FeignExceptionConstructor or at least have a public default constructor?",
                e);
        }
    }
    return preferredConstructor;
}
 
开发者ID:OpenFeign,项目名称:feign-annotation-error-decoder,代码行数:32,代码来源:ExceptionGenerator.java

示例8: findConstructor

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
 * Finds appropriate constructor which is marked with {@link Inject} annotations or no-arg one.
 *
 * @param clazz to get constructor for.
 * @param <T> any type of your instance.
 * @return constructor for creation.
 */
private static <T> Constructor<?> findConstructor(Class<T> clazz) {
    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
        if (constructor.getAnnotation(Inject.class) != null) {
            return constructor;
        }
    }
    try {
        return clazz.getDeclaredConstructor();
    }
    catch (NoSuchMethodException e) {
        throw new RuntimeException("Cannot find default constructor or constructor with Inject for " + clazz, e);
    }
}
 
开发者ID:epam,项目名称:Lagerta,代码行数:21,代码来源:Injection.java

示例9: getConstPropValues

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
private String[] getConstPropValues(Constructor<?> ctr) {
    // is constructor annotated by javax.management.ConstructorParameters ?
    ConstructorParameters ctrProps = ctr.getAnnotation(ConstructorParameters.class);
    if (ctrProps != null) {
        return ctrProps.value();
    } else {
        // try the legacy java.beans.ConstructorProperties annotation
        String[] vals = JavaBeansAccessor.getConstructorPropertiesValue(ctr);
        return vals;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:12,代码来源:DefaultMXBeanMappingFactory.java

示例10: processPropertyType

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
 * Finds the appropriate constructor for the specified type that we will use to construct
 * instances.
 */
private static void processPropertyType(final Class<?> propertyType)
        throws NoSuchMethodException, SecurityException, IntrospectionException {
    final Class<?> wrappedType = Primitives.wrap(propertyType);
    if (CONSTRUCTORS.containsKey(wrappedType)) {
        return;
    }

    // If the type is a primitive (or String type), we look for the constructor that takes a
    // single String argument, which, for primitives, validates and converts from a String
    // representation which is the form we get on ingress.
    if (propertyType.isPrimitive() || Primitives.isWrapperType(propertyType) || propertyType.equals(String.class)) {
        CONSTRUCTORS.put(wrappedType, propertyType.getConstructor(String.class));
    } else {
        // This must be a yang-defined type. We need to find the constructor that takes a
        // primitive as the only argument. This will be used to construct instances to perform
        // validation (eg range checking). The yang-generated types have a couple single-argument
        // constructors but the one we want has the bean ConstructorProperties annotation.
        for (final Constructor<?> ctor: propertyType.getConstructors()) {
            final ConstructorProperties ctorPropsAnnotation = ctor.getAnnotation(ConstructorProperties.class);
            if (ctor.getParameterTypes().length == 1 && ctorPropsAnnotation != null) {
                findYangTypeGetter(propertyType, ctorPropsAnnotation.value()[0]);
                CONSTRUCTORS.put(propertyType, ctor);
                break;
            }
        }
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:32,代码来源:DatastoreContextIntrospector.java

示例11: forConstructorOf

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
 * Returns a new injection point for the injectable constructor of {@code type}.
 *
 * @param type a concrete type with exactly one constructor annotated {@literal @}{@link Inject},
 *             or a no-arguments constructor that is not private.
 * @throws ConfigurationException if there is no injectable constructor, more than one injectable
 *                                constructor, or if parameters of the injectable constructor are malformed, such as a
 *                                parameter with multiple binding annotations.
 */
public static InjectionPoint forConstructorOf(TypeLiteral<?> type) {
    Class<?> rawType = getRawType(type.getType());
    Errors errors = new Errors(rawType);

    Constructor<?> injectableConstructor = null;
    for (Constructor<?> constructor : rawType.getConstructors()) {
        Inject inject = constructor.getAnnotation(Inject.class);
        if (inject != null) {
            if (inject.optional()) {
                errors.optionalConstructor(constructor);
            }

            if (injectableConstructor != null) {
                errors.tooManyConstructors(rawType);
            }

            injectableConstructor = constructor;
            checkForMisplacedBindingAnnotations(injectableConstructor, errors);
        }
    }

    errors.throwConfigurationExceptionIfErrorsExist();

    if (injectableConstructor != null) {
        return new InjectionPoint(type, injectableConstructor);
    }

    // If no annotated constructor is found, look for a no-arg constructor instead.
    try {
        Constructor<?> noArgConstructor = rawType.getConstructor();

        // Disallow private constructors on non-private classes (unless they have @Inject)
        if (Modifier.isPrivate(noArgConstructor.getModifiers())
                && !Modifier.isPrivate(rawType.getModifiers())) {
            errors.missingConstructor(rawType);
            throw new ConfigurationException(errors.getMessages());
        }

        checkForMisplacedBindingAnnotations(noArgConstructor, errors);
        return new InjectionPoint(type, noArgConstructor);
    } catch (NoSuchMethodException e) {
        errors.missingConstructor(rawType);
        throw new ConfigurationException(errors.getMessages());
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:55,代码来源:InjectionPoint.java

示例12: testConstructor1

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
public void testConstructor1()
{
	try
	{
		Constructor<TestClass1> ctor = TestClass1.class.getConstructor
			(new Class[] {Integer.class, String.class});
				
		Annotation[] ctor_annotations = ctor.getDeclaredAnnotations();
		assertTrue( ctor_annotations.length == 2);

		boolean[] annot_count = new boolean[] {false, false};
		for (int i=0; i<2; i++) 
		{
			assertTrue( ctor_annotations[i].annotationType().equals(A0.class)
					|| ctor_annotations[i].annotationType().equals(A5.class));
			
			if (ctor_annotations[i] instanceof A0)
			{
				annot_count[0] = true;
			}
			else if (ctor_annotations[i] instanceof A5)
			{
				annot_count[1] = true;			
			}								
		}
		
		A0 a0 = (A0) ctor.getAnnotation(A0.class);
		assertTrue (ctor.getAnnotation(A0.class).equals(a0));
		A5 a5 = (A5) ctor.getAnnotation(A5.class);
		assertTrue (ctor.getAnnotation(A5.class).equals(a5));
		
		// Make sure both @A0 and @A5 were found
		assertTrue (annot_count[0] && annot_count[1]);
				
		// Verify the annotations associated with the constructor parameters			
		Annotation[][] params = ctor.getParameterAnnotations();
		assertTrue(params.length != 0);	
		// first parameter has 1 annotation
		assertTrue(params[0].length  == 1);
		// second parameter has 4annotations			
		assertTrue(params[1].length  == 4);
		assertTrue(params[0][0] instanceof A0);
		
		annot_count = new boolean[] {false, false, false, false};
		for (int i=0; i<4; i++)
		{		
			if (params[1][i] instanceof A0)
			{
				annot_count[0] = true;
			}
			else if (params[1][i] instanceof A1)
			{
				annot_count[1] = true;
			}
			else if (params[1][i] instanceof A2)
			{
				annot_count[2] = true;
			}
			else if (params[1][i] instanceof A3)
			{
				annot_count[3] = true;
			}
		}				
		assertTrue (annot_count[0] && annot_count[1] &&
				annot_count[2] && annot_count[3]);		                                                            
	}
	catch (NoSuchMethodException e)
	{
		fail("Failed to get TestClass1 constructor (Integer, String): " + e.getMessage());
	}		
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-systemtest,代码行数:72,代码来源:AnnotationConstructorTests.java

示例13: forConstructorOf

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
 * Returns a new injection point for the injectable constructor of {@code type}.
 *
 * @param type a concrete type with exactly one constructor annotated {@literal @}{@link Inject},
 *             or a no-arguments constructor that is not private.
 * @throws ConfigurationException if there is no injectable constructor, more than one injectable
 *                                constructor, or if parameters of the injectable constructor are malformed, such as a
 *                                parameter with multiple binding annotations.
 */
public static InjectionPoint forConstructorOf(TypeLiteral<?> type) {
    Class<?> rawType = getRawType(type.getType());
    Errors errors = new Errors(rawType);

    Constructor<?> injectableConstructor = null;
    for (Constructor<?> constructor : rawType.getDeclaredConstructors()) {
        Inject inject = constructor.getAnnotation(Inject.class);
        if (inject != null) {
            if (inject.optional()) {
                errors.optionalConstructor(constructor);
            }

            if (injectableConstructor != null) {
                errors.tooManyConstructors(rawType);
            }

            injectableConstructor = constructor;
            checkForMisplacedBindingAnnotations(injectableConstructor, errors);
        }
    }

    errors.throwConfigurationExceptionIfErrorsExist();

    if (injectableConstructor != null) {
        return new InjectionPoint(type, injectableConstructor);
    }

    // If no annotated constructor is found, look for a no-arg constructor instead.
    try {
        Constructor<?> noArgConstructor = rawType.getDeclaredConstructor();

        // Disallow private constructors on non-private classes (unless they have @Inject)
        if (Modifier.isPrivate(noArgConstructor.getModifiers())
                && !Modifier.isPrivate(rawType.getModifiers())) {
            errors.missingConstructor(rawType);
            throw new ConfigurationException(errors.getMessages());
        }

        checkForMisplacedBindingAnnotations(noArgConstructor, errors);
        return new InjectionPoint(type, noArgConstructor);
    } catch (NoSuchMethodException e) {
        errors.missingConstructor(rawType);
        throw new ConfigurationException(errors.getMessages());
    }
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:55,代码来源:InjectionPoint.java

示例14: createMethodMapping

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
private static Map<Method, AssistedConstructor<?>> createMethodMapping(
        TypeLiteral<?> factoryType, TypeLiteral<?> implementationType) {
    List<AssistedConstructor<?>> constructors = new ArrayList<>();

    for (Constructor<?> constructor : implementationType.getRawType().getDeclaredConstructors()) {
        if (constructor.getAnnotation(AssistedInject.class) != null) {
            @SuppressWarnings("unchecked") // the constructor type and implementation type agree
                    AssistedConstructor assistedConstructor = new AssistedConstructor(
                    constructor, implementationType.getParameterTypes(constructor));
            constructors.add(assistedConstructor);
        }
    }

    if (constructors.isEmpty()) {
        return ImmutableMap.of();
    }

    Method[] factoryMethods = factoryType.getRawType().getMethods();

    if (constructors.size() != factoryMethods.length) {
        throw newConfigurationException("Constructor mismatch: %s has %s @AssistedInject "
                + "constructors, factory %s has %s creation methods", implementationType,
                constructors.size(), factoryType, factoryMethods.length);
    }

    Map<ParameterListKey, AssistedConstructor> paramsToConstructor = Maps.newHashMap();

    for (AssistedConstructor c : constructors) {
        if (paramsToConstructor.containsKey(c.getAssistedParameters())) {
            throw new RuntimeException("Duplicate constructor, " + c);
        }
        paramsToConstructor.put(c.getAssistedParameters(), c);
    }

    Map<Method, AssistedConstructor<?>> result = Maps.newHashMap();
    for (Method method : factoryMethods) {
        if (!method.getReturnType().isAssignableFrom(implementationType.getRawType())) {
            throw newConfigurationException("Return type of method %s is not assignable from %s",
                    method, implementationType);
        }

        List<Type> parameterTypes = new ArrayList<>();
        for (TypeLiteral<?> parameterType : factoryType.getParameterTypes(method)) {
            parameterTypes.add(parameterType.getType());
        }
        ParameterListKey methodParams = new ParameterListKey(parameterTypes);

        if (!paramsToConstructor.containsKey(methodParams)) {
            throw newConfigurationException("%s has no @AssistInject constructor that takes the "
                    + "@Assisted parameters %s in that order. @AssistInject constructors are %s",
                    implementationType, methodParams, paramsToConstructor.values());
        }

        method.getParameterAnnotations();
        for (Annotation[] parameterAnnotations : method.getParameterAnnotations()) {
            for (Annotation parameterAnnotation : parameterAnnotations) {
                if (parameterAnnotation.annotationType() == Assisted.class) {
                    throw newConfigurationException("Factory method %s has an @Assisted parameter, which "
                            + "is incompatible with the deprecated @AssistedInject annotation. Please replace "
                            + "@AssistedInject with @Inject on the %s constructor.",
                            method, implementationType);
                }
            }
        }

        AssistedConstructor matchingConstructor = paramsToConstructor.remove(methodParams);

        result.put(method, matchingConstructor);
    }
    return result;
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:72,代码来源:FactoryProvider.java

示例15: getAnnotationValue

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
private static String[] getAnnotationValue(Constructor<?> constructor) {
    ConstructorProperties annotation = constructor.getAnnotation(ConstructorProperties.class);
    return (annotation != null)
            ? annotation.value()
            : null;
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:7,代码来源:MetaData.java


注:本文中的java.lang.reflect.Constructor.getAnnotation方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。