本文整理汇总了Java中java.lang.reflect.Proxy类的典型用法代码示例。如果您正苦于以下问题:Java Proxy类的具体用法?Java Proxy怎么用?Java Proxy使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Proxy类属于java.lang.reflect包,在下文中一共展示了Proxy类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getDescriptiveType
import java.lang.reflect.Proxy; //导入依赖的package包/类
/**
* Return a descriptive name for the given object's type: usually simply
* the class name, but component type class name + "[]" for arrays,
* and an appended list of implemented interfaces for JDK proxies.
* @param value the value to introspect
* @return the qualified name of the class
*/
public static String getDescriptiveType(Object value) {
if (value == null) {
return null;
}
Class<?> clazz = value.getClass();
if (Proxy.isProxyClass(clazz)) {
StringBuilder result = new StringBuilder(clazz.getName());
result.append(" implementing ");
Class<?>[] ifcs = clazz.getInterfaces();
for (int i = 0; i < ifcs.length; i++) {
result.append(ifcs[i].getName());
if (i < ifcs.length - 1) {
result.append(',');
}
}
return result.toString();
}
else if (clazz.isArray()) {
return getQualifiedNameForArray(clazz);
}
else {
return clazz.getName();
}
}
示例2: unwrap
import java.lang.reflect.Proxy; //导入依赖的package包/类
/**
* Returns an object that implements the given interface to allow access to
* non-standard methods, or standard methods not exposed by the proxy. The
* result may be either the object found to implement the interface or a
* proxy for that object. If the receiver implements the interface then that
* is the object. If the receiver is a wrapper and the wrapped object
* implements the interface then that is the object. Otherwise the object is
* the result of calling <code>unwrap</code> recursively on the wrapped
* object. If the receiver is not a wrapper and does not implement the
* interface, then an <code>SQLException</code> is thrown.
*
* @param iface
* A Class defining an interface that the result must implement.
* @return an object that implements the interface. May be a proxy for the
* actual implementing object.
* @throws java.sql.SQLException
* If no object found that implements the interface
* @since 1.6
*/
public synchronized <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException {
try {
if ("java.sql.Connection".equals(iface.getName()) || "java.sql.Wrapper.class".equals(iface.getName())) {
return iface.cast(this);
}
if (unwrappedInterfaces == null) {
unwrappedInterfaces = new HashMap<Class<?>, Object>();
}
Object cachedUnwrapped = unwrappedInterfaces.get(iface);
if (cachedUnwrapped == null) {
cachedUnwrapped = Proxy.newProxyInstance(this.mc.getClass().getClassLoader(), new Class<?>[] { iface },
new ConnectionErrorFiringInvocationHandler(this.mc));
unwrappedInterfaces.put(iface, cachedUnwrapped);
}
return iface.cast(cachedUnwrapped);
} catch (ClassCastException cce) {
throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
}
}
示例3: checkPackageAccess
import java.lang.reflect.Proxy; //导入依赖的package包/类
private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) {
final SecurityManager s = System.getSecurityManager();
if (s != null) {
final ClassLoader cl = getClassLoader0();
if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
String name = this.getName();
int i = name.lastIndexOf('.');
if (i != -1) {
// skip the package access check on a proxy class in default proxy package
String pkg = name.substring(0, i);
if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
s.checkPackageAccess(pkg);
}
}
}
// check package access on the proxy interfaces
if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
}
}
}
示例4: wrap
import java.lang.reflect.Proxy; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@NonNull
public <V extends TiView> V wrap(@NonNull final V view) {
Class<?> foundInterfaceClass =
getInterfaceOfClassExtendingGivenInterface(view.getClass(), TiView.class);
if (foundInterfaceClass == null) {
throw new IllegalStateException("the interface extending View could not be found");
}
if (!hasObjectMethodWithAnnotation(view, DistinctUntilChanged.class)) {
// not method has the annotation, returning original view
// not creating a proxy
return view;
}
return (V) Proxy.newProxyInstance(
foundInterfaceClass.getClassLoader(), new Class<?>[]{foundInterfaceClass},
new DistinctUntilChangedInvocationHandler<>(view));
}
示例5: checkInput
import java.lang.reflect.Proxy; //导入依赖的package包/类
@Override
public ObjectInputFilter.Status checkInput(FilterInfo filter) {
Class<?> serialClass = filter.serialClass();
System.out.printf(" checkInput: class: %s, arrayLen: %d, refs: %d, depth: %d, bytes; %d%n",
serialClass, filter.arrayLength(), filter.references(),
filter.depth(), filter.streamBytes());
count++;
if (serialClass != null) {
if (serialClass.getName().contains("$$Lambda$")) {
// TBD: proper identification of serialized Lambdas?
// Fold the serialized Lambda into the SerializedLambda type
classes.add(SerializedLambda.class);
} else if (Proxy.isProxyClass(serialClass)) {
classes.add(Proxy.class);
} else {
classes.add(serialClass);
}
}
this.maxArray = Math.max(this.maxArray, filter.arrayLength());
this.maxRefs = Math.max(this.maxRefs, filter.references());
this.maxDepth = Math.max(this.maxDepth, filter.depth());
this.maxBytes = Math.max(this.maxBytes, filter.streamBytes());
return ObjectInputFilter.Status.UNDECIDED;
}
示例6: monitorNotifications
import java.lang.reflect.Proxy; //导入依赖的package包/类
/**
* Test the monitor notifications.
*/
public int monitorNotifications() throws Exception {
server = MBeanServerFactory.newMBeanServer();
MBeanServerForwarderInvocationHandler mbsfih =
(MBeanServerForwarderInvocationHandler)
Proxy.getInvocationHandler(server);
mbsfih.setGetAttributeException(
new RuntimeException("Test RuntimeException"));
domain = server.getDefaultDomain();
obsObjName = ObjectName.getInstance(domain + ":type=ObservedObject");
server.registerMBean(new ObservedObject(), obsObjName);
echo(">>> ----------------------------------------");
int error = counterMonitorNotification();
echo(">>> ----------------------------------------");
error += gaugeMonitorNotification();
echo(">>> ----------------------------------------");
error += stringMonitorNotification();
echo(">>> ----------------------------------------");
return error;
}
示例7: proxyIfInterfaceIsJdbc
import java.lang.reflect.Proxy; //导入依赖的package包/类
/**
* Recursively checks for interfaces on the given object to determine
* if it implements a java.sql interface, and if so, proxies the
* instance so that we can catch and fire SQL errors.
*
* @param toProxy
* @param clazz
*/
private Object proxyIfInterfaceIsJdbc(Object toProxy, Class<?> clazz) {
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> iclass : interfaces) {
String packageName = Util.getPackageName(iclass);
if ("java.sql".equals(packageName) || "javax.sql".equals(packageName)) {
return Proxy.newProxyInstance(toProxy.getClass().getClassLoader(), interfaces, new ConnectionErrorFiringInvocationHandler(toProxy));
}
return proxyIfInterfaceIsJdbc(toProxy, iclass);
}
return toProxy;
}
示例8: getInterfaceProxyHelper
import java.lang.reflect.Proxy; //导入依赖的package包/类
@Override
protected Object getInterfaceProxyHelper(ContextFactory cf,
Class<?>[] interfaces)
{
// XXX: How to handle interfaces array withclasses from different
// class loaders? Using cf.getApplicationClassLoader() ?
ClassLoader loader = interfaces[0].getClassLoader();
Class<?> cl = Proxy.getProxyClass(loader, interfaces);
Constructor<?> c;
try {
c = cl.getConstructor(new Class[] { InvocationHandler.class });
} catch (NoSuchMethodException ex) {
// Should not happen
throw Kit.initCause(new IllegalStateException(), ex);
}
return c;
}
示例9: processXmlElement
import java.lang.reflect.Proxy; //导入依赖的package包/类
private void processXmlElement(List<Annotation> jaxb, String elemName, String elemNS, T type) {
XmlElement elemAnn = null;
for (Annotation a : jaxb) {
if (a.annotationType() == XmlElement.class) {
elemAnn = (XmlElement) a;
jaxb.remove(a);
break;
}
}
String name = (elemAnn != null && !elemAnn.name().equals("##default"))
? elemAnn.name() : elemName;
String ns = (elemAnn != null && !elemAnn.namespace().equals("##default"))
? elemAnn.namespace() : elemNS;
boolean nillable = nav.isArray(type)
|| (elemAnn != null && elemAnn.nillable());
boolean required = elemAnn != null && elemAnn.required();
XmlElementHandler handler = new XmlElementHandler(name, ns, nillable, required);
XmlElement elem = (XmlElement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[]{XmlElement.class}, handler);
jaxb.add(elem);
}
示例10: getSerialFields
import java.lang.reflect.Proxy; //导入依赖的package包/类
/**
* Returns ObjectStreamField array describing the serializable fields of
* the given class. Serializable fields backed by an actual field of the
* class are represented by ObjectStreamFields with corresponding non-null
* Field objects. Throws InvalidClassException if the (explicitly
* declared) serializable fields are invalid.
*/
private static ObjectStreamField[] getSerialFields(Class<?> cl)
throws InvalidClassException
{
ObjectStreamField[] fields;
if (Serializable.class.isAssignableFrom(cl) &&
!Externalizable.class.isAssignableFrom(cl) &&
!Proxy.isProxyClass(cl) &&
!cl.isInterface())
{
if ((fields = getDeclaredSerialFields(cl)) == null) {
fields = getDefaultSerialFields(cl);
}
Arrays.sort(fields);
} else {
fields = NO_FIELDS;
}
return fields;
}
示例11: testIsJdbcInterface
import java.lang.reflect.Proxy; //导入依赖的package包/类
/**
* Tests Util.isJdbcInterface()
*
* @throws Exception
*/
public void testIsJdbcInterface() throws Exception {
// Classes directly or indirectly implementing JDBC interfaces.
assertTrue(Util.isJdbcInterface(PreparedStatement.class));
assertTrue(Util.isJdbcInterface(StatementImpl.class));
assertTrue(Util.isJdbcInterface(Statement.class));
assertTrue(Util.isJdbcInterface(ResultSetImpl.class));
Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { Statement.class }, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return null;
}
});
assertTrue(Util.isJdbcInterface(s.getClass()));
// Classes not implementing JDBC interfaces.
assertFalse(Util.isJdbcInterface(Util.class));
assertFalse(Util.isJdbcInterface(UtilsTest.class));
}
示例12: createProxy
import java.lang.reflect.Proxy; //导入依赖的package包/类
/**
* Returns Rest API implementation.
*
* @param restApiClass type of Rest API
* @param <T> Rest Api type
* @return Rest API instance
*/
@SuppressWarnings("unchecked")
public static <T extends Controller> T createProxy(Class<T> restApiClass) {
AssertHelper.notNull(restApiClass);
if (!restApiClass.isAnnotationPresent(RestApi.class)) {
throw new RestApiAnnotationIsMissingException(restApiClass);
}
RestApi restApiAnnotation = restApiClass.getAnnotation(RestApi.class);
String applicationName = restApiAnnotation.value();
if (StringHelper.isNullOrEmpty(applicationName)) {
throw new ApplicationNameCannotBeNullOrEmptyException(restApiClass);
}
InvocationHandler handler = new RestApiProxyInvocationHandler();
T restApi = (T) Proxy.newProxyInstance(restApiClass.getClassLoader(),
new Class[]{restApiClass},
handler);
return restApi;
}
示例13: generateProxyType
import java.lang.reflect.Proxy; //导入依赖的package包/类
private static Object generateProxyType(final int i) {
class DummyH implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("equals")) {
return proxy == args[0];
}
if (method.getName().equals("toString")) {
return "DummyH[" + i + "]";
}
return null;
}
}
return Proxy.newProxyInstance(
MetaInfCache.class.getClassLoader(),
findTypes(i),
new DummyH()
);
}
示例14: getInstance
import java.lang.reflect.Proxy; //导入依赖的package包/类
/**
* Use this method to get existing or new non-initialized instance of
* BlacklistedClassesHandler. This method ensures that only one instance of
* BlacklistedClassesHandler is shared across the different classloaders.
*
* Use initSingleton methods to initialize BlacklistedClassesHandler
* @return existing or new non-initialized instance of
* BlacklistedClassesHandler
*/
public static synchronized BlacklistedClassesHandler getInstance() {
if (instance == null) {
try {
// TODO Is it really necessary to use proxies?
ClassLoader myClassLoader = BlacklistedClassesHandlerSingleton.class.getClassLoader();
ClassLoader parentClassLoader = ClassLoader.getSystemClassLoader();
if (myClassLoader != parentClassLoader) {
Class otherClassInstance = parentClassLoader.loadClass(BlacklistedClassesHandlerSingleton.class.getName());
Method getInstanceMethod = otherClassInstance.getDeclaredMethod("getInstance", new Class[] { });
Object otherAbsoluteSingleton = getInstanceMethod.invoke(null, new Object[] { } );
instance = (BlacklistedClassesHandler) Proxy.newProxyInstance(myClassLoader,
new Class[] { BlacklistedClassesHandler.class },
new PassThroughProxyHandler(otherAbsoluteSingleton));
} else {
instance = new BlacklistedClassesHandlerSingleton();
}
} catch (Exception e) {
throw new RuntimeException("Failed to get BlacklistedClassesHandler instance", e);
}
}
return instance;
}
示例15: invokeObjectMethod
import java.lang.reflect.Proxy; //导入依赖的package包/类
/**
* Handles java.lang.Object methods.
**/
private Object invokeObjectMethod(Object proxy,
Method method,
Object[] args)
{
String name = method.getName();
if (name.equals("hashCode")) {
return hashCode();
} else if (name.equals("equals")) {
Object obj = args[0];
return
proxy == obj ||
(obj != null &&
Proxy.isProxyClass(obj.getClass()) &&
equals(Proxy.getInvocationHandler(obj)));
} else if (name.equals("toString")) {
return proxyToString(proxy);
} else {
throw new IllegalArgumentException(
"unexpected Object method: " + method);
}
}