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


Java Constructor.isAccessible方法代码示例

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


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

示例1: newInstance

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
public static <T> T newInstance(Constructor<T> constructor, boolean access, Object... params) {
    try {
        boolean wasAccess = constructor.isAccessible();

        if (!wasAccess && access) {
            constructor.setAccessible(true);
        }

        T instance = constructor.newInstance(params);

        if (!wasAccess && access) {
            constructor.setAccessible(false);
        }

        return instance;
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException exception) {
        exception.printStackTrace();
    }

    return null;
}
 
开发者ID:Dragovorn,项目名称:gamecraft,代码行数:22,代码来源:Reflection.java

示例2: assertUtilityClassWellDefined

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
 * Verifies that a utility class is well defined.
 * @param clazz utility class to verify.
 * @see <a href="http://stackoverflow.com/a/10872497/4271064">Stack Overflow</a>
 */
static void assertUtilityClassWellDefined(Class<?> clazz) throws Exception {
    Assert.assertTrue("Class must be final", Modifier.isFinal(clazz.getModifiers()));
    Assert.assertEquals(
            "Only one constructor allowed", 1,
            clazz.getDeclaredConstructors().length
    );

    Constructor<?> constructor = clazz.getDeclaredConstructor();
    if (constructor.isAccessible() || !Modifier.isPrivate(constructor.getModifiers())) {
        Assert.fail("Constructor is not private");
    }
    constructor.setAccessible(true);
    constructor.newInstance();
    constructor.setAccessible(false);

    for (Method method : clazz.getMethods())
        if (!Modifier.isStatic(method.getModifiers()))
            if (method.getDeclaringClass().equals(clazz))
                Assert.fail("There exists a non-static method: " + method);
}
 
开发者ID:mosmetro-android,项目名称:module-captcha-recognition,代码行数:26,代码来源:UtilityClasses.java

示例3: create

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
private Date create(Class<? extends Date> type, long time) throws Exception {
    if (type == Date.class || type == null) {
        return new Date(time);
    }
    if (type == Timestamp.class) {
        return new Timestamp(time);
    }
    if (type == java.sql.Date.class) {
        return new java.sql.Date(time);
    }
    if (type == Time.class) {
        return new Time(time);
    }
    try {
        Constructor<? extends Date> constructor = type.getConstructor(long.class);
        if (!constructor.isAccessible()) {
            try {
                constructor.setAccessible(true);
            } catch (SecurityException se) {
            }
        }
        return constructor.newInstance(time);
    } catch (Exception ex) {
        return new Date(time);
    }
}
 
开发者ID:bruce-cloud,项目名称:fastclone,代码行数:27,代码来源:DateCloner.java

示例4: findConstructor

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
 * Locates a given constructor anywhere in the class inheritance hierarchy.
 *
 * @param instance       an object to search the constructor into.
 * @param parameterTypes constructor parameter types
 * @return a constructor object
 * @throws NoSuchMethodException if the constructor cannot be located
 */
public static Constructor<?> findConstructor(Object instance, Class<?>... parameterTypes)
        throws NoSuchMethodException {
    for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
        try {
            Constructor<?> ctor = clazz.getDeclaredConstructor(parameterTypes);

            if (!ctor.isAccessible()) {
                ctor.setAccessible(true);
            }

            return ctor;
        } catch (NoSuchMethodException e) {
            // ignore and search next
        }
    }

    throw new NoSuchMethodException("Constructor"
            + " with parameters "
            + Arrays.asList(parameterTypes)
            + " not found in " + instance.getClass());
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:30,代码来源:ShareReflectUtil.java

示例5: addMethodProxy

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
private void addMethodProxy(Class<?> hookType) {
    try {
        Constructor<?> constructor = hookType.getDeclaredConstructors()[0];
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        MethodProxy methodProxy;
        if (constructor.getParameterTypes().length == 0) {
            methodProxy = (MethodProxy) constructor.newInstance();
        } else {
            methodProxy = (MethodProxy) constructor.newInstance(this);
        }
        mInvocationStub.addMethodProxy(methodProxy);
    } catch (Throwable e) {
        throw new RuntimeException("Unable to instance Hook : " + hookType + " : " + e.getMessage());
    }
}
 
开发者ID:coding-dream,项目名称:TPlayer,代码行数:18,代码来源:MethodInvocationProxy.java

示例6: isAWellDefinedUtilityClass

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
public UtilityClassAssertions isAWellDefinedUtilityClass() {
	Assertions.assertThat(Modifier.isFinal(actual.getModifiers())).describedAs("A utility class should be marked as final.").isTrue();
	Assertions.assertThat(actual.getDeclaredConstructors().length).describedAs("A utility class should only have one constructor, but this class has " + actual.getDeclaredConstructors().length).isEqualTo(1);

	try {
		Constructor<?> constructor = actual.getDeclaredConstructor();
		if (constructor.isAccessible() || !Modifier.isPrivate(constructor.getModifiers())) {
			Assertions.fail("The constructor is not private.");
		}

		constructor.setAccessible(true);
		constructor.newInstance();
		constructor.setAccessible(false);

		for (Method method : actual.getMethods()) {
			if (!Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass().equals(actual)) {
				Assertions.fail("A utility class should not have instance methods, but found: " + method);
			}
		}
	}
	catch (Exception e) {
		Assertions.fail("An error occurred while inspecting the class.");
	}

	return this;
}
 
开发者ID:PatternFM,项目名称:tokamak,代码行数:27,代码来源:UtilityClassAssertions.java

示例7: createInstance

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
@NotNull
static <T> T createInstance(@NotNull Class<T> wantedType, @NotNull Class[] parameterTypes, @NotNull Object[] parameterValues) {
    try {
        Constructor<T> constructor = wantedType.getDeclaredConstructor(parameterTypes);
        boolean accessible = constructor.isAccessible();
        if (!accessible) {
            constructor.setAccessible(true);
        }
        try {
            return constructor.newInstance(parameterValues);
        } finally {
            if (!accessible) {
                constructor.setAccessible(false);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:dumptruckman,项目名称:dtmlibs,代码行数:20,代码来源:InstanceUtil.java

示例8: getCoder

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
 * Retrieve a {@link StateCoder} from an annotation and the annotated class.
 *
 * @param saveState           annotation obtained from the annotated field
 * @param annotatedFieldClass java class of the annotate field
 * @return not null coder used to serialize and deserialize the state {@link Bundle}
 * @throws CoderNotFoundException if the coder can't be found or is unsupported
 */
@NonNull
@Override
public StateCoder getCoder(@NonNull SaveState saveState, @NonNull Class<?> annotatedFieldClass) throws CoderNotFoundException {
    StateCoder stateCoder;
    // Get the coder class from the annotation.
    final Class<? extends StateCoder> stateSDClass = saveState.value();
    if (GsonCoder.class.isAssignableFrom(stateSDClass)) {
        try {
            Constructor<? extends StateCoder> constructor;
            // The constructor must have one argument of Gson type.
            constructor = stateSDClass.getConstructor(Gson.class);
            boolean accessible = constructor.isAccessible();
            // If the constructor can't be accessed, it will be modified in accessible and will return inaccessible after.
            if (!accessible) {
                constructor.setAccessible(true);
            }
            // Creates the instance.
            stateCoder = constructor.newInstance(mGson);
            if (!accessible) {
                constructor.setAccessible(false);
            }
        } catch (Exception e) {
            throw new RuntimeException("You must provide an instance of " + GsonCoder.class.getName());
        }
    } else {
        // Use default implementation.
        stateCoder = super.getCoder(saveState, annotatedFieldClass);
    }
    return stateCoder;
}
 
开发者ID:Fondesa,项目名称:Lyra,代码行数:39,代码来源:DefaultGsonCoderRetriever.java

示例9: verifyPrivateConstructor

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
private static void verifyPrivateConstructor(final Class<?> clazz)
        throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
    assertEquals("There must be only one constructor", 1, clazz.getDeclaredConstructors().length);
    final Constructor<?> constructor = clazz.getDeclaredConstructor();
    if (constructor.isAccessible() || !Modifier.isPrivate(constructor.getModifiers())) {
        fail("constructor is not private");
    }
    callPrivateConstructor(constructor);
}
 
开发者ID:streamingpool,项目名称:streamingpool-core,代码行数:10,代码来源:TestUtil.java

示例10: getCoder

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
 * Retrieve a {@link StateCoder} from an annotation and the annotated class.
 *
 * @param saveState           annotation obtained from the annotated field
 * @param annotatedFieldClass java class of the annotate field
 * @return not null coder used to serialize and deserialize the state {@link Bundle}
 * @throws CoderNotFoundException if the coder can't be found or is unsupported
 */
@NonNull
@Override
public StateCoder getCoder(@NonNull SaveState saveState, @NonNull Class<?> annotatedFieldClass) throws CoderNotFoundException {
    StateCoder stateCoder;
    // Get the coder class from the annotation.
    final Class<? extends StateCoder> stateSDClass = saveState.value();
    if (stateSDClass == StateCoder.class) {
        // Get the coder from cache, if present.
        stateCoder = mCachedCoders.get(annotatedFieldClass);
        if (stateCoder != null)
            return stateCoder;

        // Get the coder if it's supported by default or throw a new CoderNotFoundException.
        stateCoder = StateCoderUtils.getBasicCoderForClass(annotatedFieldClass);
        // Put the coder in cache.
        mCachedCoders.put(annotatedFieldClass, stateCoder);
    } else {
        // A custom coder won't be cached to support multiple implementations for the same class.
        try {
            Constructor<? extends StateCoder> constructor = stateSDClass.getConstructor();
            boolean accessible = constructor.isAccessible();
            // If the constructor can't be accessed, it will be modified in accessible and will return inaccessible after.
            if (!accessible) {
                constructor.setAccessible(true);
            }
            // Creates the instance.
            stateCoder = constructor.newInstance();
            if (!accessible) {
                constructor.setAccessible(false);
            }
        } catch (Exception e) {
            throw new RuntimeException("Cannot instantiate a " + StateCoder.class.getSimpleName() +
                    " of class " + stateSDClass.getName());
        }
    }
    return stateCoder;
}
 
开发者ID:Fondesa,项目名称:Lyra,代码行数:46,代码来源:DefaultCoderRetriever.java

示例11: setConstructorAccessible

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
@Nullable
static <T> Constructor<T> setConstructorAccessible(Constructor<T> constructor) {
    try {
        if (!constructor.isAccessible()) constructor.setAccessible(true);
        return constructor;
    }
    catch (SecurityException ignored){}
    return null;
}
 
开发者ID:mikroskeem,项目名称:Shuriken,代码行数:10,代码来源:Reflect.java

示例12: newInstance

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
 * Create a new instance by finding a constructor that matches the argumentTypes signature 
 * using the arguments for instantiation.
 * 
 * @param implClass Full classname of class to create
 * @param argumentTypes The constructor argument types
 * @param arguments The constructor arguments
 * @return a new instance
 * @throws IllegalArgumentException if className, argumentTypes, or arguments are null
 * @throws RuntimeException if any exceptions during creation
 * @author <a href="mailto:[email protected]">Aslak Knutsen</a>
 * @author <a href="mailto:[email protected]">ALR</a>
 */
static <T> T newInstance(final Class<T> implClass, final Class<?>[] argumentTypes, final Object[] arguments)
{
   if (implClass == null)
   {
      throw new IllegalArgumentException("ImplClass must be specified");
   }
   if (argumentTypes == null)
   {
      throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments");
   }
   if (arguments == null)
   {
      throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments");
   }
   final T obj;
   try
   {
      final Constructor<T> constructor = getConstructor(implClass, argumentTypes);
      if(!constructor.isAccessible()) {
         AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
               constructor.setAccessible(true);
               return null;
            }
         });
      }
      obj = constructor.newInstance(arguments);
   }
   catch (Exception e)
   {
      throw new RuntimeException("Could not create new instance of " + implClass, e);
   }

   return obj;
}
 
开发者ID:arquillian,项目名称:arquillian-reporter,代码行数:49,代码来源:SecurityActions.java

示例13: a

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
private <T> ae<T> a(Class<? super T> cls) {
    try {
        Constructor declaredConstructor = cls.getDeclaredConstructor(new Class[0]);
        if (!declaredConstructor.isAccessible()) {
            declaredConstructor.setAccessible(true);
        }
        return new l(this, declaredConstructor);
    } catch (NoSuchMethodException e) {
        return null;
    }
}
 
开发者ID:JackChan1999,项目名称:letv,代码行数:12,代码来源:f.java

示例14: newInstance

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
 * Create a new instance by finding a constructor that matches the argumentTypes signature
 * using the arguments for instantiation.
 *
 * @param implClass
 *     Full classname of class to create
 * @param argumentTypes
 *     The constructor argument types
 * @param arguments
 *     The constructor arguments
 *
 * @return a new instance
 *
 * @throws IllegalArgumentException
 *     if className, argumentTypes, or arguments are null
 * @throws RuntimeException
 *     if any exceptions during creation
 */
static <T> T newInstance(final Class<T> implClass, final Class<?>[] argumentTypes,
    final Object[] arguments) {
    if (implClass == null) {
        throw new IllegalArgumentException("ImplClass must be specified");
    }
    if (argumentTypes == null) {
        throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments");
    }
    if (arguments == null) {
        throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments");
    }
    final T obj;
    try {
        final Constructor<T> constructor = getConstructor(implClass, argumentTypes);
        if (!constructor.isAccessible()) {
            AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
                constructor.setAccessible(true);
                return null;
            });
        }
        obj = constructor.newInstance(arguments);
    } catch (Exception e) {
        throw new RuntimeException("Could not create new instance of " + implClass, e);
    }

    return obj;
}
 
开发者ID:arquillian,项目名称:smart-testing,代码行数:46,代码来源:SecurityUtils.java

示例15: createTreeMap

import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
 * 创建TreeMap
 *
 * @param type       集合类型
 * @param comparator 比较器
 * @return 新的TreeMap
 */
private TreeMap createTreeMap(Class<? extends Map> type, Comparator comparator) throws Exception {
    if (type != TreeMap.class && type != null) {
        Constructor constructor = type.getConstructor(Comparator.class);
        if (!constructor.isAccessible()) {
            try {
                constructor.setAccessible(true);
            } catch (SecurityException se) {
            }
        }
        return (TreeMap) constructor.newInstance(comparator);
    }
    return new TreeMap(comparator);
}
 
开发者ID:bruce-cloud,项目名称:fastclone,代码行数:21,代码来源:TreeMapCloner.java


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