我的目标是从class
创建一个实例,该实例实现一个interface
并扩展另一个class
。
...实体注释:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface Entity {
String visibileName();
}
...实现IEventDesignDialog
public class EventDesignDialog implements IEventDesignDialog{
private String show;
private String dateAndTimeDisplayFormat;
private String eventType;
@Entity(visibileName = "Show")
public String getShow() {
return this.show;
}
@Entity(visibileName = "Date And Time display format")
public String getDateAndTimeDisplayFormat() {
return this.dateAndTimeDisplayFormat;
}
@Entity(visibileName = "Event Type")
public String getEventType() {
System.out.println("get event type method invokde successfully");
return this.eventType;
}
}
IEventDesignDialog
界面:
public interface IEventDesignDialog extends IPage{
public String getShow();
public String getDateAndTimeDisplayFormat();
public String getEventType();
}
IPage
界面:
public interface IPage {
}
动态代理实现:
public class IPageProxy implements InvocationHandler {
private List<Method> entityMethods;
private Class <? extends IPage> screenClazz;
public IPageProxy(final Class <? extends IPage> screenClazz) {
entityMethods = new ArrayList<>();
getEntityAnnotatedMethods(screenClazz);
// Accept the real implementation to be proxied
this.screenClazz = screenClazz;
}
/**
* create an page instance
* @param type
* @param
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static IPage getInstance(final Class<? extends IPage> type)
throws InstantiationException, IllegalAccessException {
List<Class<?>> interfaces = new ArrayList<>();
interfaces.addAll(Arrays.asList(type.getInterfaces()));
return (IPage) Proxy.newProxyInstance(
type.getClassLoader(),
findInterfaces(type),
new IPageProxy(type)
);
/*return (IPage) Proxy.newProxyInstance(type.getClassLoader(),
interfaces.toArray(new Class<?>[interfaces.size()])
, new IPageProxy(type));*/
}
/**
* get all methods that annotated with @Entity annotation
* and add it for entityMethods array List
* @param screenClazz
*/
private void getEntityAnnotatedMethods(final Class <? extends IPage> screenClazz) {
// Scan each interface method for the specific annotation
// and save each compatible method
for (final Method m : screenClazz.getDeclaredMethods()) {
if (m.isAnnotationPresent(Entity.class)) {
entityMethods.add(m);
}
}
}
static Class<?>[] findInterfaces(final Class<? extends IPage> type) {
Class<?> current = type;
do {
final Class<?>[] interfaces = current.getInterfaces();
if (interfaces.length != 0) {
return interfaces;
}
} while ((current = current.getSuperclass()) != Object.class);
throw new UnsupportedOperationException("The type does not implement any interface");
}
@Override
public Object invoke(
final Object proxy,
final Method method,
final Object[] args) throws InvocationTargetException, IllegalAccessException {
// A method on MyInterface has been called!
// Check if we need to go call it directly or if we need to
// execute something else before!
if (entityMethods.contains(method)) {
// The method exist in our to-be-proxied list
// Execute something and the call it
// ... some other things
System.out.println("Something else");
}
// Invoke original method
return method.invoke(screenClazz, args);
}
}
主类:
public class Main {
public static void main(String[] args) {
try {
((EventDesignDialog)getInstance(EventDesignDialog.class)).getEventType();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static <T extends IPage> T getInstance(final Class<? extends IPage> type) throws InstantiationException, IllegalAccessException {
return (T) IPageProxy.getInstance(type);
}
}
引发以下异常:
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy2 cannot be cast to abc.EventDesignDialog
at abc.Main.main(Main.java:8)
答案 0 :(得分:2)
您正在扩展 Screen
,这意味着它不是interface
。
仅当基础interface
存在于层次结构中时,动态代理才能工作。
interfaces.size() == 0
因此,代理无法实现任何interface
,并且显然它不是Screen
层次结构的一部分。
如果Screen
是interface
,则您的方法仍然太复杂。这个
public static Screen getInstance(Class<? extends Screen> type)
足够了。
您仍然收到例外情况,因为
Class#getInterfaces
返回由此类类实现的interface
。
这意味着,如果您在EventDesignDialog.class
上调用它,它将返回一个空数组。
这意味着,即使您在EntityDesignDialog.class
上调用它,它仍然会返回一个空数组。
在Screen.class
上调用它时,它将返回
[IPage.class]
您需要使用以下内容来循环层次结构
Class#getSuperclass
直到找到合适的interface
。
可能的实现可能看起来像
static Class<?>[] findInterfaces(final Class<?> type) {
Class<?> current = type;
do {
final Class<?>[] interfaces = current.getInterfaces();
if (interfaces.length != 0) {
return interfaces;
}
} while ((current = current.getSuperclass()) != Object.class);
throw new UnsupportedOperationException("The type does not implement any interface");
}
这意味着您需要将代码更改为
return (IPage) Proxy.newProxyInstance(
type.getClassLoader(),
findInterfaces(type),
new IPageProxy(type)
);
但是,由于您已经知道结果将是IPage
代理,因此您可以
return (IPage) Proxy.newProxyInstance(
type.getClassLoader(),
new Class[] { IPage.class },
new IPageProxy(type)
);
这里
public static IPage getInstance(final Class<? extends IPage> type)
您要返回IPage
,但是在这里
((EventDesignDialog)getInstance(EventDesignDialog.class))
您正尝试对其进行降级,这意味着您正尝试将其转换为更具体的类型。这是不可能的,因为代理服务器的类型不是EventDesignDialog
,而是仅实现了IPage
接口。
由于Dynamic Proxies基于接口,因此您将不得不处理接口。
尝试强制转换为具体类将始终引发异常。
如果您需要IEventDesignDialog
,则需要专门用于它的新代理。