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


Java Reflection类代码示例

本文整理汇总了Java中sun.reflect.Reflection的典型用法代码示例。如果您正苦于以下问题:Java Reflection类的具体用法?Java Reflection怎么用?Java Reflection使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: getDrivers

import sun.reflect.Reflection; //导入依赖的package包/类
/**
 * Retrieves an Enumeration with all of the currently loaded JDBC drivers
 * to which the current caller has access.
 *
 * <P><B>Note:</B> The classname of a driver can be found using
 * <CODE>d.getClass().getName()</CODE>
 *
 * @return the list of JDBC Drivers loaded by the caller's class loader
 */
@CallerSensitive
public static java.util.Enumeration<Driver> getDrivers() {
    java.util.Vector<Driver> result = new java.util.Vector<>();

    Class<?> callerClass = Reflection.getCallerClass();

    // Walk through the loaded registeredDrivers.
    for(DriverInfo aDriver : registeredDrivers) {
        // If the caller does not have permission to load the driver then
        // skip it.
        if(isDriverAllowed(aDriver.driver, callerClass)) {
            result.addElement(aDriver.driver);
        } else {
            println("    skipping: " + aDriver.getClass().getName());
        }
    }
    return (result.elements());
}
 
开发者ID:madHEYsia,项目名称:ClassroomFlipkart,代码行数:28,代码来源:DriverManager.java

示例2: getFields

import sun.reflect.Reflection; //导入依赖的package包/类
/**
 * Returns an array of <code>Field</code> objects that contains each
 * field of the object that this helper class is serializing.
 *
 * @return an array of <code>Field</code> objects
 * @throws SerialException if an error is encountered accessing
 * the serialized object
 * @throws  SecurityException  If a security manager, <i>s</i>, is present
 * and the caller's class loader is not the same as or an
 * ancestor of the class loader for the class of the
 * {@linkplain #getObject object} being serialized
 * and invocation of {@link SecurityManager#checkPackageAccess
 * s.checkPackageAccess()} denies access to the package
 * of that class.
 * @see Class#getFields
 */
@CallerSensitive
public Field[] getFields() throws SerialException {
    if (fields != null) {
        Class<?> c = this.obj.getClass();
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            /*
             * Check if the caller is allowed to access the specified class's package.
             * If access is denied, throw a SecurityException.
             */
            Class<?> caller = sun.reflect.Reflection.getCallerClass();
            if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
                                                    c.getClassLoader())) {
                ReflectUtil.checkPackageAccess(c);
            }
        }
        return c.getFields();
    } else {
        throw new SerialException("SerialJavaObject does not contain" +
            " a serialized object instance");
    }
}
 
开发者ID:madHEYsia,项目名称:ClassroomFlipkart,代码行数:39,代码来源:SerialJavaObject.java

示例3: privateGetDeclaredMethods

import sun.reflect.Reflection; //导入依赖的package包/类
private Method[] privateGetDeclaredMethods(boolean publicOnly) {
    checkInitted();
    Method[] res;
    ReflectionData<T> rd = reflectionData();
    if (rd != null) {
        res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
        if (res != null) return res;
    }
    // No cached value available; request value from VM
    res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
    if (rd != null) {
        if (publicOnly) {
            rd.declaredPublicMethods = res;
        } else {
            rd.declaredMethods = res;
        }
    }
    return res;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:20,代码来源:Class.java

示例4: getInvocationHandler

import sun.reflect.Reflection; //导入依赖的package包/类
/**
 * Returns the invocation handler for the specified proxy instance.
 *
 * @param   proxy the proxy instance to return the invocation handler for
 * @return  the invocation handler for the proxy instance
 * @throws  IllegalArgumentException if the argument is not a
 *          proxy instance
 * @throws  SecurityException if a security manager, <em>s</em>, is present
 *          and the caller's class loader is not the same as or an
 *          ancestor of the class loader for the invocation handler
 *          and invocation of {@link SecurityManager#checkPackageAccess
 *          s.checkPackageAccess()} denies access to the invocation
 *          handler's class.
 */
@CallerSensitive
public static InvocationHandler getInvocationHandler(Object proxy)
    throws IllegalArgumentException
{
    /*
     * Verify that the object is actually a proxy instance.
     */
    if (!isProxyClass(proxy.getClass())) {
        throw new IllegalArgumentException("not a proxy instance");
    }

    final Proxy p = (Proxy) proxy;
    final InvocationHandler ih = p.h;
    if (System.getSecurityManager() != null) {
        Class<?> ihClass = ih.getClass();
        Class<?> caller = Reflection.getCallerClass();
        if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
                                                ihClass.getClassLoader()))
        {
            ReflectUtil.checkPackageAccess(ihClass);
        }
    }

    return ih;
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:40,代码来源:Proxy.java

示例5: testNonSystemMethod

import sun.reflect.Reflection; //导入依赖的package包/类
@CallerSensitive
private void testNonSystemMethod() {
    try {
        Class<?> c = Reflection.getCallerClass();
        throw new RuntimeException("@CallerSensitive testNonSystemMethods not supported");
    } catch (InternalError e) {
        StackTraceElement[] stackTrace = e.getStackTrace();
        checkStackTrace(stackTrace, e);
        if (!stackTrace[1].getClassName().equals(GetCallerClassTest.class.getName()) ||
            !stackTrace[1].getMethodName().equals("testNonSystemMethod")) {
            throw new RuntimeException("Unexpected error: " + e.getMessage(), e);
        }
        if (!stackTrace[2].getClassName().equals(GetCallerClassTest.class.getName()) ||
            !stackTrace[2].getMethodName().equals("main")) {
            throw new RuntimeException("Unexpected error: " + e.getMessage(), e);
        }
        System.out.println("Expected error: " + e.getMessage());
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:20,代码来源:GetCallerClassTest.java

示例6: slowCheckMemberAccess

import sun.reflect.Reflection; //导入依赖的package包/类
void slowCheckMemberAccess(Class<?> caller, Class<?> clazz, Object obj, int modifiers,
                           Class<?> targetClass)
    throws IllegalAccessException
{
    Reflection.ensureMemberAccess(caller, clazz, obj, modifiers);

    // Success: Update the cache.
    Object cache = ((targetClass == clazz)
                    ? caller
                    : new Class<?>[] { caller, targetClass });

    // Note:  The two cache elements are not volatile,
    // but they are effectively final.  The Java memory model
    // guarantees that the initializing stores for the cache
    // elements will occur before the volatile write.
    securityCheckCache = cache;         // write volatile
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:18,代码来源:AccessibleObject.java

示例7: main

import sun.reflect.Reflection; //导入依赖的package包/类
public static void main (String [] args){
	try{
		System.out.println("Class: " + Reflection.getCallerClass(1).getName());
		ObjectMapper mapper = new ObjectMapper();
		List<User> users = mapper.readValue(new URL("http://jsonplaceholder.typicode.com/users"), 
			new TypeReference<List<User>>(){});

		for ( User user: users){
			System.out.println("Name: " + user.name + ", Company: " + user.company.name);
		}
	}catch(Exception ex){
		ex.printStackTrace();
	}
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Cookbook,代码行数:15,代码来源:Sample.java

示例8: checkCallerClass

import sun.reflect.Reflection; //导入依赖的package包/类
@CallerSensitive
private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) {
    // This method is called via MH_checkCallerClass and so it's
    // correct to ask for the immediate caller here.
    Class<?> actual = Reflection.getCallerClass();
    if (actual != expected && actual != expected2)
        throw new InternalError("found "+actual.getName()+", expected "+expected.getName()
                                +(expected == expected2 ? "" : ", or else "+expected2.getName()));
    return true;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:11,代码来源:MethodHandleImpl.java

示例9: getDriver

import sun.reflect.Reflection; //导入依赖的package包/类
/**
 * Attempts to locate a driver that understands the given URL.
 * The <code>DriverManager</code> attempts to select an appropriate driver from
 * the set of registered JDBC drivers.
 *
 * @param url a database URL of the form
 *     <code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
 * @return a <code>Driver</code> object representing a driver
 * that can connect to the given URL
 * @exception SQLException if a database access error occurs
 */
@CallerSensitive
public static Driver getDriver(String url)
    throws SQLException {

    println("DriverManager.getDriver(\"" + url + "\")");

    Class<?> callerClass = Reflection.getCallerClass();

    // Walk through the loaded registeredDrivers attempting to locate someone
    // who understands the given URL.
    for (DriverInfo aDriver : registeredDrivers) {
        // If the caller does not have permission to load the driver then
        // skip it.
        if(isDriverAllowed(aDriver.driver, callerClass)) {
            try {
                if(aDriver.driver.acceptsURL(url)) {
                    // Success!
                    println("getDriver returning " + aDriver.driver.getClass().getName());
                return (aDriver.driver);
                }

            } catch(SQLException sqe) {
                // Drop through and try the next driver.
            }
        } else {
            println("    skipping: " + aDriver.driver.getClass().getName());
        }

    }

    println("getDriver: no suitable driver");
    throw new SQLException("No suitable driver", "08001");
}
 
开发者ID:madHEYsia,项目名称:ClassroomFlipkart,代码行数:45,代码来源:DriverManager.java

示例10: deregisterDriver

import sun.reflect.Reflection; //导入依赖的package包/类
/**
 * Removes the specified driver from the {@code DriverManager}'s list of
 * registered drivers.
 * <p>
 * If a {@code null} value is specified for the driver to be removed, then no
 * action is taken.
 * <p>
 * If a security manager exists and its {@code checkPermission} denies
 * permission, then a {@code SecurityException} will be thrown.
 * <p>
 * If the specified driver is not found in the list of registered drivers,
 * then no action is taken.  If the driver was found, it will be removed
 * from the list of registered drivers.
 * <p>
 * If a {@code DriverAction} instance was specified when the JDBC driver was
 * registered, its deregister method will be called
 * prior to the driver being removed from the list of registered drivers.
 *
 * @param driver the JDBC Driver to remove
 * @exception SQLException if a database access error occurs
 * @throws SecurityException if a security manager exists and its
 * {@code checkPermission} method denies permission to deregister a driver.
 *
 * @see SecurityManager#checkPermission
 */
@CallerSensitive
public static synchronized void deregisterDriver(Driver driver)
    throws SQLException {
    if (driver == null) {
        return;
    }

    SecurityManager sec = System.getSecurityManager();
    if (sec != null) {
        sec.checkPermission(DEREGISTER_DRIVER_PERMISSION);
    }

    println("DriverManager.deregisterDriver: " + driver);

    DriverInfo aDriver = new DriverInfo(driver, null);
    if(registeredDrivers.contains(aDriver)) {
        if (isDriverAllowed(driver, Reflection.getCallerClass())) {
            DriverInfo di = registeredDrivers.get(registeredDrivers.indexOf(aDriver));
             // If a DriverAction was specified, Call it to notify the
             // driver that it has been deregistered
             if(di.action() != null) {
                 di.action().deregister();
             }
             registeredDrivers.remove(aDriver);
        } else {
            // If the caller does not have permission to load the driver then
            // throw a SecurityException.
            throw new SecurityException();
        }
    } else {
        println("    couldn't find driver to unload");
    }
}
 
开发者ID:madHEYsia,项目名称:ClassroomFlipkart,代码行数:59,代码来源:DriverManager.java

示例11: getEnclosingClass

import sun.reflect.Reflection; //导入依赖的package包/类
/**
 * Returns the immediately enclosing class of the underlying
 * class.  If the underlying class is a top level class this
 * method returns {@code null}.
 * @return the immediately enclosing class of the underlying class
 * @exception  SecurityException
 *             If a security manager, <i>s</i>, is present and the caller's
 *             class loader is not the same as or an ancestor of the class
 *             loader for the enclosing class and invocation of {@link
 *             SecurityManager#checkPackageAccess s.checkPackageAccess()}
 *             denies access to the package of the enclosing class
 * @since 1.5
 */
@CallerSensitive
public Class<?> getEnclosingClass() throws SecurityException {
    // There are five kinds of classes (or interfaces):
    // a) Top level classes
    // b) Nested classes (static member classes)
    // c) Inner classes (non-static member classes)
    // d) Local classes (named classes declared within a method)
    // e) Anonymous classes


    // JVM Spec 4.8.6: A class must have an EnclosingMethod
    // attribute if and only if it is a local class or an
    // anonymous class.
    EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
    Class<?> enclosingCandidate;

    if (enclosingInfo == null) {
        // This is a top level or a nested class or an inner class (a, b, or c)
        enclosingCandidate = getDeclaringClass();
    } else {
        Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
        // This is a local class or an anonymous class (d or e)
        if (enclosingClass == this || enclosingClass == null)
            throw new InternalError("Malformed enclosing method information");
        else
            enclosingCandidate = enclosingClass;
    }

    if (enclosingCandidate != null)
        enclosingCandidate.checkPackageAccess(
                ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
    return enclosingCandidate;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:47,代码来源:Class.java

示例12: getClasses

import sun.reflect.Reflection; //导入依赖的package包/类
/**
 * Returns an array containing {@code Class} objects representing all
 * the public classes and interfaces that are members of the class
 * represented by this {@code Class} object.  This includes public
 * class and interface members inherited from superclasses and public class
 * and interface members declared by the class.  This method returns an
 * array of length 0 if this {@code Class} object has no public member
 * classes or interfaces.  This method also returns an array of length 0 if
 * this {@code Class} object represents a primitive type, an array
 * class, or void.
 *
 * @return the array of {@code Class} objects representing the public
 *         members of this class
 * @throws SecurityException
 *         If a security manager, <i>s</i>, is present and
 *         the caller's class loader is not the same as or an
 *         ancestor of the class loader for the current class and
 *         invocation of {@link SecurityManager#checkPackageAccess
 *         s.checkPackageAccess()} denies access to the package
 *         of this class.
 *
 * @since JDK1.1
 */
@CallerSensitive
public Class<?>[] getClasses() {
    checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);

    // Privileged so this implementation can look at DECLARED classes,
    // something the caller might not have privilege to do.  The code here
    // is allowed to look at DECLARED classes because (1) it does not hand
    // out anything other than public members and (2) public member access
    // has already been ok'd by the SecurityManager.

    return java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<Class<?>[]>() {
            public Class<?>[] run() {
                List<Class<?>> list = new ArrayList<>();
                Class<?> currentClass = Class.this;
                while (currentClass != null) {
                    Class<?>[] members = currentClass.getDeclaredClasses();
                    for (int i = 0; i < members.length; i++) {
                        if (Modifier.isPublic(members[i].getModifiers())) {
                            list.add(members[i]);
                        }
                    }
                    currentClass = currentClass.getSuperclass();
                }
                return list.toArray(new Class<?>[0]);
            }
        });
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:52,代码来源:Class.java

示例13: getType

import sun.reflect.Reflection; //导入依赖的package包/类
/**
 * Get the type of the field.  If the type is non-primitive and this
 * <code>ObjectStreamField</code> was obtained from a deserialized {@link
 * ObjectStreamClass} instance, then <code>Object.class</code> is returned.
 * Otherwise, the <code>Class</code> object for the type of the field is
 * returned.
 *
 * @return  a <code>Class</code> object representing the type of the
 *          serializable field
 */
@CallerSensitive
public Class<?> getType() {
    if (System.getSecurityManager() != null) {
        Class<?> caller = Reflection.getCallerClass();
        if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(), type.getClassLoader())) {
            ReflectUtil.checkPackageAccess(type);
        }
    }
    return type;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:21,代码来源:ObjectStreamField.java

示例14: main

import sun.reflect.Reflection; //导入依赖的package包/类
public static void main() {
    // in jdk.unsupported
    Class<?> caller = Reflection.getCallerClass(2);

    // removed
    JPEGCodec r = new JPEGCodec();

    // removed
    SoftCache s = new SoftCache();

    // removed
    Service.providers(S.class);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:14,代码来源:Main.java

示例15: ensureAnnotationPresent

import sun.reflect.Reflection; //导入依赖的package包/类
private static void ensureAnnotationPresent(Class<?> c, String name, boolean cs)
    throws NoSuchMethodException
{
    Method m = c.getDeclaredMethod(name);
    if (!m.isAnnotationPresent(CallerSensitive.class)) {
        throw new RuntimeException("@CallerSensitive not present in method " + m);
    }
    if (Reflection.isCallerSensitive(m) != cs) {
        throw new RuntimeException("Unexpected: isCallerSensitive returns " +
            Reflection.isCallerSensitive(m));
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:13,代码来源:GetCallerClassTest.java


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