java.lang.Class类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(241)

本文整理了Java中java.lang.Class类的一些代码示例,展示了Class类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Class类的具体详情如下:
包路径:java.lang.Class
类名称: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.

Class instances representing object types (classes or interfaces)

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).

Classes representing primitive types

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:

  • B representing the byte primitive type
  • S representing the short primitive type
  • I representing the int primitive type
  • J representing the long primitive type
  • F representing the float primitive type
  • D representing the double primitive type
  • C representing the char primitive type
  • Z representing the boolean primitive type
  • V representing void function return values
Classes representing array classes

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:

  • [I representing the int[] type
  • [Ljava/lang/String; representing the String[] type
  • [[[C representing the char[][][] type (three dimensions!)
    [中]Java类在内存中的表示形式。这种表示作为查询类相关信息的起点,这一过程通常称为“反射”。基本上有三种类型的ClassInstance:表示实类和接口的ClassInstance、表示基元类型的ClassInstance和表示数组类的ClassInstance。
    #####表示对象类型(类或接口)的类实例
    它们表示类层次结构中的普通类或接口。与这些类实例关联的名称只是它所表示的类或接口的完全限定类名。除了这个人类可读的名称外,每个类还与一个所谓的签名相关联,即字母“L”,后跟类名和分号(“;”)。签名是运行时系统在内部用于标识类的内容(例如在DEX文件中)。
    #####表示基元类型的类
    它们表示标准Java基元类型,因此共享它们的名称(例如int基元类型的“int”)。尽管无法基于这些类实例创建新实例,但它们对于提供反射信息和作为数组类的组件类型仍然很有用。每个基元类型都有一个类实例,它们的签名是:
    *B表示字节基元类型
    *S表示短基元类型
    *I表示int基元类型
    *J表示长基元类型
    *F表示浮点基元类型
    *D表示双基元类型
    *C表示char原语类型
    *Z表示布尔基元类型
    *表示void函数返回值的V
    #####表示数组类的类
    这些表示Java数组的类。数组叶组件类型和arity(维数)的每个组合都有一个这样的Classinstance。在这种情况下,与类关联的名称由一个或多个左方括号(数组中每个维度一个)组成,后跟表示叶组件类型的类的签名,叶组件类型可以是对象类型,也可以是基元类型。表示数组类型的类的签名与其名称相同。数组类签名的示例如下:
    *[I]表示int[]类型
    *[Ljava/lang/String;表示字符串[]类型
    *[[[C表示字符[][]类型(三维!)

代码示例

代码示例来源: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);
 }
}

相关文章

Class类方法