本文整理了Java中java.lang.Class
类的一些代码示例,展示了Class
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Class
类的具体详情如下:
包路径:java.lang.Class
类名称:Class
[英]The in-memory representation of a Java class. This representation serves as the starting point for querying class-related information, a process usually called "reflection". There are basically three types of Classinstances: those representing real classes and interfaces, those representing primitive types, and those representing array classes.
These represent an ordinary class or interface as found in the class hierarchy. The name associated with these Class instances is simply the fully qualified class name of the class or interface that it represents. In addition to this human-readable name, each class is also associated by a so-called signature, which is the letter "L", followed by the class name and a semicolon (";"). The signature is what the runtime system uses internally for identifying the class (for example in a DEX file).
These represent the standard Java primitive types and hence share their names (for example "int" for the int primitive type). Although it is not possible to create new instances based on these Class instances, they are still useful for providing reflection information, and as the component type of array classes. There is one Class instance for each primitive type, and their signatures are:
These represent the classes of Java arrays. There is one such Classinstance per combination of array leaf component type and arity (number of dimensions). In this case, the name associated with the Classconsists of one or more left square brackets (one per dimension in the array) followed by the signature of the class representing the leaf component type, which can be either an object type or a primitive type. The signature of a Class representing an array type is the same as its name. Examples of array class signatures are:
代码示例来源:origin: stackoverflow.com
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
代码示例来源:origin: ReactiveX/RxJava
/**
* Appends the class name to a non-null value.
* @param o the object
* @return the string representation
*/
public static String valueAndClass(Object o) {
if (o != null) {
return o + " (class: " + o.getClass().getSimpleName() + ")";
}
return "null";
}
代码示例来源:origin: square/okhttp
@Override public void configureTlsExtensions(
SSLSocket sslSocket, String hostname, List<Protocol> protocols) {
List<String> names = alpnProtocolNames(protocols);
try {
Object alpnProvider = Proxy.newProxyInstance(Platform.class.getClassLoader(),
new Class[] {clientProviderClass, serverProviderClass}, new AlpnProvider(names));
putMethod.invoke(null, sslSocket, alpnProvider);
} catch (InvocationTargetException | IllegalAccessException e) {
throw new AssertionError("failed to set ALPN", e);
}
}
代码示例来源:origin: spring-projects/spring-framework
private static boolean isPresent(String className) {
try {
Class.forName(className, false, LogAdapter.class.getClassLoader());
return true;
}
catch (ClassNotFoundException ex) {
return false;
}
}
代码示例来源:origin: google/guava
private static <T> T newProxy(Class<T> interfaceType, InvocationHandler handler) {
Object object =
Proxy.newProxyInstance(
interfaceType.getClassLoader(), new Class<?>[] {interfaceType}, handler);
return interfaceType.cast(object);
}
代码示例来源:origin: apache/incubator-dubbo
private Object readResolve() {
try {
Class c = Class.forName("java.time.Duration");
Method m = c.getDeclaredMethod("ofSeconds", long.class, long.class);
return m.invoke(null, seconds, nanos);
} catch (Throwable t) {
// ignore
}
return null;
}
}
代码示例来源:origin: google/guava
private void checkHelperVersion(ClassLoader classLoader, String expectedHelperClassName)
throws Exception {
// Make sure we are actually running with the expected helper implementation
Class<?> abstractFutureClass = classLoader.loadClass(AbstractFuture.class.getName());
Field helperField = abstractFutureClass.getDeclaredField("ATOMIC_HELPER");
helperField.setAccessible(true);
assertEquals(expectedHelperClassName, helperField.get(null).getClass().getSimpleName());
}
代码示例来源:origin: google/guava
private void runTestMethod(ClassLoader classLoader) throws Exception {
Class<?> test = classLoader.loadClass(FuturesTest.class.getName());
Object testInstance = test.newInstance();
test.getMethod("setUp").invoke(testInstance);
test.getMethod(getName()).invoke(testInstance);
test.getMethod("tearDown").invoke(testInstance);
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void testManualProxyJavaWithStaticPointcutAndTwoClassLoaders() throws Exception {
LogUserAdvice logAdvice = new LogUserAdvice();
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(String.format("execution(* %s.TestService.*(..))", getClass().getName()));
// Test with default class loader first...
testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, new TestServiceImpl(), "TestServiceImpl");
// Then try again with a different class loader on the target...
SimpleThrowawayClassLoader loader = new SimpleThrowawayClassLoader(new TestServiceImpl().getClass().getClassLoader());
// Make sure the interface is loaded from the parent class loader
loader.excludeClass(TestService.class.getName());
loader.excludeClass(TestException.class.getName());
TestService other = (TestService) loader.loadClass(TestServiceImpl.class.getName()).newInstance();
testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, other, "TestServiceImpl");
}
代码示例来源:origin: spring-projects/spring-framework
private static void ensureSpringRulesAreNotPresent(Class<?> testClass) {
for (Field field : testClass.getFields()) {
Assert.state(!SpringClassRule.class.isAssignableFrom(field.getType()), () -> String.format(
"Detected SpringClassRule field in test class [%s], " +
"but SpringClassRule cannot be used with the SpringJUnit4ClassRunner.", testClass.getName()));
Assert.state(!SpringMethodRule.class.isAssignableFrom(field.getType()), () -> String.format(
"Detected SpringMethodRule field in test class [%s], " +
"but SpringMethodRule cannot be used with the SpringJUnit4ClassRunner.", testClass.getName()));
}
}
代码示例来源:origin: apache/incubator-dubbo
protected Object instantiate()
throws Exception {
try {
if (_constructor != null)
return _constructor.newInstance(_constructorArgs);
else
return _type.newInstance();
} catch (Exception e) {
throw new HessianProtocolException("'" + _type.getName() + "' could not be instantiated", e);
}
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public boolean matches(Method method, Class<?> targetClass) {
if (TransactionalProxy.class.isAssignableFrom(targetClass) ||
PlatformTransactionManager.class.isAssignableFrom(targetClass) ||
PersistenceExceptionTranslator.class.isAssignableFrom(targetClass)) {
return false;
}
TransactionAttributeSource tas = getTransactionAttributeSource();
return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
代码示例来源:origin: google/guava
private static ResourceInfo resourceInfo(Class<?> cls) {
String resource = cls.getName().replace('.', '/') + ".class";
ClassLoader loader = cls.getClassLoader();
return ResourceInfo.of(resource, loader);
}
代码示例来源:origin: iluwatar/java-design-patterns
private static Class<?> getCommandClass(String request) {
Class<?> result;
try {
result = Class.forName("com.iluwatar.front.controller." + request + "Command");
} catch (ClassNotFoundException e) {
result = UnknownCommand.class;
}
return result;
}
}
代码示例来源:origin: square/okhttp
public CertificateChainCleaner buildCertificateChainCleaner(X509TrustManager trustManager) {
try {
Class<?> extensionsClass = Class.forName("android.net.http.X509TrustManagerExtensions");
Constructor<?> constructor = extensionsClass.getConstructor(X509TrustManager.class);
Object extensions = constructor.newInstance(trustManager);
Method checkServerTrusted = extensionsClass.getMethod(
"checkServerTrusted", X509Certificate[].class, String.class, String.class);
return new AndroidCertificateChainCleaner(extensions, checkServerTrusted);
} catch (Exception e) {
throw new AssertionError(e);
}
}
代码示例来源:origin: alibaba/druid
public void setStatLoggerClassName(String className) {
Class<?> clazz;
try {
clazz = Class.forName(className);
DruidDataSourceStatLogger statLogger = (DruidDataSourceStatLogger) clazz.newInstance();
this.setStatLogger(statLogger);
} catch (Exception e) {
throw new IllegalArgumentException(className, e);
}
}
代码示例来源:origin: greenrobot/EventBus
@Override
public SubscriberInfo getSuperSubscriberInfo() {
if(superSubscriberInfoClass == null) {
return null;
}
try {
return superSubscriberInfoClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
代码示例来源:origin: apache/incubator-dubbo
private static boolean isZoneId(Class cl) {
try {
return isJava8() && Class.forName("java.time.ZoneId").isAssignableFrom(cl);
} catch (ClassNotFoundException e) {
// ignore
}
return false;
}
代码示例来源:origin: google/guava
public void testToString() {
assertEquals(int[].class.getName(), Types.toString(int[].class));
assertEquals(int[][].class.getName(), Types.toString(int[][].class));
assertEquals(String[].class.getName(), Types.toString(String[].class));
Type elementType = List.class.getTypeParameters()[0];
assertEquals(elementType.toString(), Types.toString(elementType));
}
代码示例来源:origin: square/okhttp
@Override public boolean isCleartextTrafficPermitted(String hostname) {
try {
Class<?> networkPolicyClass = Class.forName("android.security.NetworkSecurityPolicy");
Method getInstanceMethod = networkPolicyClass.getMethod("getInstance");
Object networkSecurityPolicy = getInstanceMethod.invoke(null);
return api24IsCleartextTrafficPermitted(hostname, networkPolicyClass, networkSecurityPolicy);
} catch (ClassNotFoundException | NoSuchMethodException e) {
return super.isCleartextTrafficPermitted(hostname);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new AssertionError("unable to determine cleartext support", e);
}
}
内容来源于网络,如有侵权,请联系作者删除!