[英]How to cast from super class to derived class in field injected by CDI?
我正在將JSF 2.1與CDI和JBoss 7.1.1結合使用
是否可以在超類變量principal
注入CDI並轉換為派生類? 在示例中, MyUserPrincipal
是派生類。 如果我編寫@Inject Principal principal
則從調試(和重載toString()方法)中知道, MyUserPrincipal
代理類將注入到變量principal
。 但是我無法將此實例轉換為MyUserPrincipal
實例。
下面我嘗試解決問題的2種方法:
public class MyUserPrincipal implements Principal, Serializible{
MyUserPrincipal (String name){
}
public myMethod() { }
}
//Attempt 1:
public class MyCdiClass2 implements Serializable{
//MyUserPrincipal proxy instance will be injected.
@Inject Principal principal;
@PostConstruct init() {
MyUserPrincipal myPrincipal = (MyUserPrincipal) pincipal; //<--- Fails to cast! (b)
myPrincipal.myMethod();
}
}
//Attempt 2:
public class MyCdiClass1 implements Serializable{
@Inject MyUserPrincipal myPrincipal; //<---- Fails to inject! (a)
@PostConstruct init() {
//do something with myPrincipal
}
}
如果您沒有生產者,那么您要注入的實際上是擴展容器提供的委托人的代理。 實現同一接口的兩個類的分配與該接口類型的字段兼容,但是您不能將其強制轉換為另一個。
也就是說,似乎您想覆蓋內置的主體bean。 據我所知,您只能使用CDI 1.0之前的替代產品以及CDI 1.1中的裝飾器來實現這一目標,請參閱CDI-164 。
替代示例:
package com.example;
@Alternative
public class MyUserPrincipal implements Principal, Serializible {
// ...
@Override
public String getName() {
// ...
}
}
// and beans.xml
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd“> com.example.MyUserPrincipal
裝飾器示例:
@Decorator
public class MyUserPrincipal implements Principal, Serializible {
@Inject @Delegate private Principal delegate;
// other methods
@Override
public String getName() {
// simply delegate or extend
return this.delegate.getName();
}
}
// again plus appropriate beans.xml
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.