Dynamic [Runtime] type casting in Java
Hello,
This is my requirement.
I have a method that takes class name as a parameter.
Ex:
Object myMethod(String classname){
Object xyz = getObject(); //userdefine method which returns some object
/*<b>I need to typecast above object with the class name passed as the method parameter</b>*/
/*<b>How can i type cast this object</b>*/
Object obj = (classname) xyz;
return obj;
In the above example, how can i dynamically typecast the object with class whose name is passed as the method parameter?
Hello,
This is my requirement.
I have a method that takes class name as a parameter.
Ex:
Object myMethod(String classname){
Object xyz = getObject(); //userdefine method which
returns some object
/*<b>I need to typecast above object with the class
name passed as the method parameter</b>*/
/*<b>How can i type cast this object</b>*/
Object obj = (classname) xyz;
return obj;
In the above example, how can i dynamically typecast
the object with class whose name is passed as the
method parameter?Perhaps a little more background on the project (what you are trying to do) will help the experts here answer?
/*with a class that takes a noarg constructor*/
public Object getObject(String classname) throws Exception
//might want to get a bit more specific with which exceptions it will throw
return Class.forName(classname).newInstance();
}Do I think this sometimes is indicative (perhaps even more often than not), of a possible design flaw? Yes..
It gets a little trickier if you have constructors (you have to create a Class object representing the string with the .forName(..) ..and then use some reflection to determine constructors and then a bit of logic to determine which of those to use...)
~Dave
Similar Messages
-
Could not type cast in java embedding
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
org.xml.sax.InputSource in = (org.xml.sax.InputSource) getVariableData("Invoke_1_getRoutingAndFrameJumpers_OutputVariable","getRoutingAndFrameJumpersResponse");
Document doc = db.parse(in);
In the above code I am trying to type cast the variable getRoutingAndFrameJumpersResponse into org.xml.sax.InputSource so that i can parse.
I am not getting any error during compilation
but I am unable to type cast some run time error is coming in the line were I am type casting but I am not able to see the runtime error.
How can I see the runtime error in java embedding, how to type cast a variable into xml so that I can parse it.Hi Arun,
Could you try using the bpelx:rename extension in an assign activity enables a BPEL process to rename an element through use of XSD type casting.
<bpel:assign>
<bpelx:rename elementTo="QName1"? typeCastTo="QName2"?>
<bpelx:target variable="ncname" part="ncname"? query="xpath_str" />
</bpelx:rename>
</bpel:assign>
Cheers
A -
Hi,
Can we do explicit type casting vigorously in a java class? Im in a situation that i've to do explicit casting 40 to 50 times in a class. Is there any overhead for JVM or any performance issue with this?Why do you cast so often? It's sounds like a weird design. Casting is pretty cheap.
Kaj -
Dynamic class type casting?
Anyone know how to synthesize changing the type of a class after the instance is created?
I have a base class that has a number of sub classes. When instances are created, I cannot create subclass instances because the required information is not available. However, after the instances are created, I can determine the subclass I would like the instance to be.
The subclasses don't have any new fields, they just override base class methods. The subclass I want is determined by a field in the base class that is not known at base class creation time. It is set at a later point.
Any ideas?
I could delay object creation until I know exactly which sub classs I want, but that would increase code size considerably. I would like a neat mutation mechanism or something similar so I could change the type of the class.
I could also recreate the object when I know the subclass I want, but that seems expensive.I have a base class that has a number of sub classes.
When instances are created, I cannot create subclass
instances because the required information is not
available. However, after the instances are created, I
can determine the subclass I would like the instance
to be.You might consider the prototype pattern. In the prototype pattern, you have a prototype manager and prototype objects it manages. You register prototypes with the prototype manager using a key (think of a key abstractly here) and retrieve the prototypes using the same key. When you retrieve a prototype from the prototype manager you clone the prototype, which is much faster than instantiating an object, and then you use the clone.
From what you said above it seems that you have all of the right elements for application of the pattern. You said you have a base class with many sub-classes and that you know which sub-class you want when you have specific information.
>
The subclasses don't have any new fields, they just
override base class methods. The subclass I want is
determined by a field in the base class that is not
known at base class creation time. It is set at a
later point.
In implementing the pattern it would be a good idea to create a new class that manages the information you require (as previosuly determined by the field in the base class) to create a subclass, removing it (the field) from the base class completely. This new class is used as your key to retrieve prototypes from the prototype manager.public class OldBaseNowIsKey {
String field;
public String getField() { return field; }
public void setField(String s) { field = s; }
public class NewBaseClass {
public void doSomethingPolymorphic() { }
public class PrototypeOne extends NewBaseClass {
public void doSomethingPolymorphic() { }
public class PrototypeManager {
private Hashmap prototypes;
static {
// This is one way to register prototypes and not
// necessarily the best.
prototypes = new Hashmap();
prototypes.put("prototypeOneKey", new PrototypeOne());
public static NewBaseClass get(OldBaseNowIsKey key) {
return (NewBaseClass) prototypes(key.getField());
public class ClassThatUsesPrototype {
public void someMethod() {
// Something happens and we know the value of the
// field in the old base class but now we use that
// information to create a key or reuse an existing
// key object.
OldBaseNowIsKey key = new OldBaseNowIsKey();
key.setField(theInformation);
// Now we know have the necessary information to
// create a sub-class only we will be cloning which
// is faster.
NewBaseClass prototype = PrototypeManager.get(key).clone();
prototype.doSomethingPolymorphic();
I could delay object creation until I know exactly
which sub classs I want, but that would increase code
size considerably. I would like a neat mutation
mechanism or something similar so I could change the
type of the class.Sounds like C++. -
Can I do dynamic class cast with java SE1.4.2?
Hi,
I have some question on dynamic class cast.
I'm using java SE1.4.2. Suppose I have a method :
castObjectToSomething(Object o)
Something s = (Something) o;
However, I don't know what is the class to cast until runtime. How can I do a runtime class cast?
I know that java 5.0 have a Class.cast() method which java1.4.2 does not have. But can I do the same stuff by using SE1.4.2?
Thank You!!!!!
oh_sillyThere is no sense in wanting to cast to a class that is only known at runtime. Because you can't do anything with such a class during runtime. Even though you could technically retrieve the class name, the method names and the parameter names, you could do nothing with this class as you don't know what it is doing. If you would know what it can do, you would know it also during compile time and then you would know the classname/interface name you want to cast to and can import it and use it reasonably.
Tell us the requirement that you think you have and we will proof you that you don't need such a requirement. -
Can we dynamically type-cast an object reference passed to Object Clss to that specific class?
Here is what I want to do.
I am going to pass an object reference to a method, which has Object class as parameter to it, as shown below. Using getClass() or some other way, I want to dynamically typecast this reference to the original Class and call some method of this Class.
void test (Object ref1){
((ref1.getClass())ref1).writeLog();
By doing this, am I violating the basic Object Orineted rules?I mean, consider an hypothetical case (which is wrong
from OO point of view) that there are suppose 10
classes in my system. None of them related to each
other, all are independent classes. But each one has a
method called, writeLog(). Now I want to write one
method which will be called by each of these classes
(in some 11th class), which will have "Object" as a
parameter. Now using the actual reference I want to
call the corresponding writeLog() method.
1 - Point out to management that the design is now officially broken.
2 - Point out that if the design is not fixed then any solution that impliments the changes will cost more to maintain in the future and will likely lead to instabilities in the system (due to complexity.)
3 - Implement one of the suggested solutions and make sure that you put in a lot of error checking and logging in the hacked solution.
4 - Produce extensive documentation about the impact of changing any of the objects that you are relying on. Push it to anyone and everyone that might ever touch or even suggest changes to the code.
Doing all of the above allows you to live stress free when the next revision breaks because someone didn't understand the implications of your hacked solution. You will be able to find the problem quickly and point out that it had nothing to do with your code but rather because someone else did not follow the complete documentation that you produced. And then when they complain that your solution was a hack you can point out that you explained that previously as well. -
Java type casting interesting query
In java semantics
1) float var1=10.5; // is wrong it should be written as
float var1=(float)10.5; //type casting->double to float
or
float var1=10.5f; //type casting
but
2) byte var2=10; // here int to byte type casting should be there according to previous eg.
But this is correct.
Why the 2nd one is correct???>
I suspect the reason is, that the compiler can check whether it will fit in the second case.
You can't accidentally type
byte b = 128;Whereas with floating point numbers you could accidentally be losing precision, imagining that you're using doubles, when in fact you are using floats. So the extra cast is needed so you understand you're losing precision. -
TYPE003: Runtime Type Mismatch
A general question:
ODSI 10gR3
Has anyone seen the "TYPE003: Runtime Type Mismatch" error returned when you pass a variable through a function rather than a literal? The variable is the exact same value as the literal and I have casted all to a xs:double before passing through the "getReferencesByVersionID" function in code below.
=============================================================
(: Always tested with the same $VersionID and only 1 order in the database :)
for $Order in tns:getOrdersByVersionID($VersionID)
return
(: let $OrderNum := tns:getOrderNum(fn:data($Order/ns1:OrderNum)) :) (: Fail :)
let $OrderNum := xs:double(fn:data($Order/ns1:OrderNum)) (: Fail :)
(: let $OrderNum := xs:double(12001002) :) (: Success :)
let $References := tns:getReferencesByVersionID($VersionID, $OrderNum)
return
Returned XML snippet when run successfully:
<ns0:Order ns0:TransactionPurpose="ADD/UPDATE">
<ns0:ShipperRef>J10310ST12001002</ns0:ShipperRef>
<ns0:OrderNum>12001002</ns0:OrderNum> (: Populated by: "data($Order/ns1:OrderNum)". "ns0:OrderNum" defined as xs:double in schema. Note: same value as literal :)
<ns0:Comments/>
<ns0:OrderType>O</ns0:OrderType>
<ns0:Workflow>O</ns0:Workflow>
Returned Trace when not working:
com.bea.dsp.das.exception.DASException: weblogic.xml.query.exceptions.XQueryTypeException: {bea-err}TYPE003: Runtime Type Mismatch
at com.bea.dsp.das.ejb.EJBClient.invokeOperation(EJBClient.java:160)
at com.bea.dsp.das.DataAccessServiceImpl.invokeOperation(DataAccessServiceImpl.java:171)
at com.bea.dsp.das.DataAccessServiceImpl.invoke(DataAccessServiceImpl.java:122)
at com.bea.dsp.ide.xquery.views.test.QueryExecutor.invokeFunctionOrProcedure(QueryExecutor.java:113)
at com.bea.dsp.ide.xquery.views.test.XQueryTestViewContent.getFunctionExecutionResult(XQueryTestView.java:1041)
at com.bea.dsp.ide.xquery.views.test.XQueryTestViewContent.executeFunction(XQueryTestView.java:1176)
at com.bea.dsp.ide.xquery.views.test.XQueryTestViewContent.widgetSelectedImpl(XQueryTestView.java:1866)
at com.bea.dsp.ide.xquery.views.test.XQueryTestViewContent.access$300(XQueryTestView.java:174)
at com.bea.dsp.ide.xquery.views.test.XQueryTestViewContent$3.run(XQueryTestView.java:1594)
at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:67)
at com.bea.dsp.ide.xquery.views.test.XQueryTestViewContent.widgetSelectedBusy(XQueryTestView.java:1597)
at com.bea.dsp.ide.xquery.views.test.XQueryTestViewContent.widgetSelected(XQueryTestView.java:1560)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:227)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:66)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:938)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3687)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3298)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2389)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2353)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2219)
at org.eclipse.ui.internal.Workbench$4.run(Workbench.java:466)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:289)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:461)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:106)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:169)
The obvious answer is that "fn:data($Order/ns1:OrderNum)" does not equal "xs:double(12001002)" when passed through the " tns:getReferencesByVersionID()" function but it appears to be the same value.
This is happening in the Application layer so too much to include all the code. Thoughts/Comments on where to look or what I am missing?
Thanks
TomThanks Mike. No other web services... all physical ODSI to a single Oracle 11g denormalized table, selected several times to get different parts of the data (order header, shipping info, items, etc) and bubbled up through the layers via transformations finally getting into a single XML ORDER at the app layer.
I'm not a guru at reading traces but it appears numieric vs double issue?
The full stack trace:
weblogic.xml.query.exceptions.XQueryTypeException: {bea-err}TYPE003: Runtime Type Mismatch
at weblogic.xml.query.runtime.core.ExecutionWrapper.asXQueryException(ExecutionWrapper.java:165)
at weblogic.xml.query.runtime.core.ExecutionWrapper.fetchNext(ExecutionWrapper.java:94)
at weblogic.xml.query.iterators.GenericIterator.hasNext(GenericIterator.java:133)
at weblogic.xml.query.runtime.node.DeflateRec.fetchNext(DeflateRec.java:43)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at com.bea.ld.server.ResultPusher$ChunkyBinxmlChunker.nextChunk(ResultPusher.java:402)
at com.bea.ld.server.ResultPusher$AsyncChunkyBinxmlChunker.nextChunk(ResultPusher.java:520)
at com.bea.ld.server.ResultPusher$BinxmlChunker.next(ResultPusher.java:292)
at com.bea.ld.EJBRequestHandler$1.next(EJBRequestHandler.java:938)
at com.bea.ld.ServerBean.maybeStreamResult(ServerBean.java:97)
at com.bea.ld.ServerBean.executeOperationStreaming(ServerBean.java:86)
at com.bea.ld.Server_ydm4ie_EOImpl.executeOperationStreaming(Server_ydm4ie_EOImpl.java:72)
at com.bea.ld.Server_ydm4ie_EOImpl_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:589)
at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:477)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:473)
at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
java.lang.ClassCastException: weblogic.xml.query.tokens.basic.Basic_StringToken
at weblogic.xml.query.runtime.numeric.compare.DoubleEqual.compare(DoubleEqual.java:31)
at weblogic.xml.query.runtime.compare.ComparisonIterator.execute(ComparisonIterator.java:45)
at weblogic.xml.query.iterators.FunctionIterator.fetchNext(FunctionIterator.java:30)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.logic.BoolEffValue.exec(BoolEffValue.java:47)
at weblogic.xml.query.runtime.logic.BoolEffValue.execute(BoolEffValue.java:43)
at weblogic.xml.query.iterators.FunctionIterator.fetchNext(FunctionIterator.java:30)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.IfThenElse.fetchNext(IfThenElse.java:79)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.CountMapIterator.fetchNext(CountMapIterator.java:167)
at weblogic.xml.query.iterators.GenericIterator.peekNext(GenericIterator.java:163)
at weblogic.xml.query.runtime.constructor.SuperElementConstructor.getPhase2(SuperElementConstructor.java:388)
at weblogic.xml.query.runtime.constructor.PartMatElemConstructor.matEverything(PartMatElemConstructor.java:123)
at weblogic.xml.query.runtime.constructor.PartMatElemConstructor.fetchNext(PartMatElemConstructor.java:197)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.IfThenElse.fetchNext(IfThenElse.java:91)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.IfThenElse.fetchNext(IfThenElse.java:91)
at weblogic.xml.query.iterators.GenericIterator.peekNext(GenericIterator.java:163)
at weblogic.xml.query.runtime.navigation.ChildPath.fetchNext(ChildPath.java:221)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.iterators.BasicMaterializedTokenStream.next(BasicMaterializedTokenStream.java:109)
at weblogic.xml.query.iterators.BasicMaterializedTokenStream$MatStreamIterator.fetchNext(BasicMaterializedTokenStream.java:448)
at weblogic.xml.query.iterators.LegacyGenericIterator.next(LegacyGenericIterator.java:109)
at weblogic.xml.query.runtime.core.RTVariable.fetchNext(RTVariable.java:53)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.sequences.Exists.execute(Exists.java:37)
at weblogic.xml.query.iterators.FunctionIterator.fetchNext(FunctionIterator.java:30)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.IfThenElse.fetchNext(IfThenElse.java:79)
at weblogic.xml.query.iterators.GenericIterator.peekNext(GenericIterator.java:163)
at weblogic.xml.query.runtime.constructor.SuperElementConstructor.getPhase2(SuperElementConstructor.java:388)
at weblogic.xml.query.runtime.constructor.PartMatElemConstructor.matEverything(PartMatElemConstructor.java:123)
at weblogic.xml.query.runtime.constructor.PartMatElemConstructor.fetchNext(PartMatElemConstructor.java:197)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.iterators.BasicMaterializedTokenStream.next(BasicMaterializedTokenStream.java:109)
at weblogic.xml.query.iterators.BasicMaterializedTokenStream$MatStreamIterator.fetchNext(BasicMaterializedTokenStream.java:448)
at weblogic.xml.query.iterators.LegacyGenericIterator.next(LegacyGenericIterator.java:109)
at weblogic.xml.query.runtime.core.RTVariable.fetchNext(RTVariable.java:53)
at weblogic.xml.query.iterators.GenericIterator.peekNext(GenericIterator.java:163)
at weblogic.xml.query.runtime.navigation.ChildPath.fetchNext(ChildPath.java:221)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.sequences.Exists.execute(Exists.java:37)
at weblogic.xml.query.iterators.FunctionIterator.fetchNext(FunctionIterator.java:30)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.IfThenElse.fetchNext(IfThenElse.java:79)
at weblogic.xml.query.iterators.GenericIterator.peekNext(GenericIterator.java:163)
at weblogic.xml.query.runtime.constructor.SuperElementConstructor.buildPreserveModeTextNode(SuperElementConstructor.java:320)
at weblogic.xml.query.runtime.constructor.SuperElementConstructor.getPhase2(SuperElementConstructor.java:405)
at weblogic.xml.query.runtime.constructor.PartMatElemConstructor.matEverything(PartMatElemConstructor.java:123)
at weblogic.xml.query.runtime.constructor.PartMatElemConstructor.fetchNext(PartMatElemConstructor.java:197)
at weblogic.xml.query.iterators.GenericIterator.peekNext(GenericIterator.java:163)
at weblogic.xml.query.runtime.constructor.SuperElementConstructor.getPhase2(SuperElementConstructor.java:388)
at weblogic.xml.query.runtime.constructor.PartMatElemConstructor.fetchNext(PartMatElemConstructor.java:229)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.LetIterator.fetchNext(LetIterator.java:133)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.LetIterator.fetchNext(LetIterator.java:133)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.LetIterator.fetchNext(LetIterator.java:133)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.LetIterator.fetchNext(LetIterator.java:133)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.LetIterator.fetchNext(LetIterator.java:133)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.CountMapIterator.fetchNext(CountMapIterator.java:167)
at weblogic.xml.query.iterators.GenericIterator.peekNext(GenericIterator.java:163)
at weblogic.xml.query.runtime.constructor.SuperElementConstructor.getPhase2(SuperElementConstructor.java:388)
at weblogic.xml.query.runtime.constructor.PartMatElemConstructor.fetchNext(PartMatElemConstructor.java:229)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.debug.Trace.fetchNext(Trace.java:70)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.xdbc.iterators.ItemIterator.fetchNext(ItemIterator.java:86)
at weblogic.xml.query.iterators.LegacyGenericIterator.hasNext(LegacyGenericIterator.java:130)
at weblogic.xml.query.runtime.sequences.Subsequence.fetchNext(Subsequence.java:101)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.querycide.QueryAssassin.fetchNext(QueryAssassin.java:54)
at weblogic.xml.query.iterators.GenericIterator.peekNext(GenericIterator.java:163)
at weblogic.xml.query.runtime.qname.InsertNamespaces.fetchNext(InsertNamespaces.java:237)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.ExecutionWrapper.fetchNext(ExecutionWrapper.java:88)
at weblogic.xml.query.iterators.GenericIterator.hasNext(GenericIterator.java:133)
at weblogic.xml.query.runtime.node.DeflateRec.fetchNext(DeflateRec.java:43)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at com.bea.ld.server.ResultPusher$ChunkyBinxmlChunker.nextChunk(ResultPusher.java:402)
at com.bea.ld.server.ResultPusher$AsyncChunkyBinxmlChunker.nextChunk(ResultPusher.java:520)
at com.bea.ld.server.ResultPusher$BinxmlChunker.next(ResultPusher.java:292)
at com.bea.ld.EJBRequestHandler$1.next(EJBRequestHandler.java:938)
at com.bea.ld.ServerBean.maybeStreamResult(ServerBean.java:97)
at com.bea.ld.ServerBean.executeOperationStreaming(ServerBean.java:86)
at com.bea.ld.Server_ydm4ie_EOImpl.executeOperationStreaming(Server_ydm4ie_EOImpl.java:72)
at com.bea.ld.Server_ydm4ie_EOImpl_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:589)
at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:477)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:473)
at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173) -
I'm getting an instance of a class through the newInstance() method.I want to access that class members through this newly created object.But to do this, I have to typecast the object by its class name.In my case, the class is a dynamic one(i.e., unknown at the time of creating that object).I get the class name as a string through the getName() method.
HOW CAN I DO THE TYPE CASTING OR IS THERE ANY OTHER METHOD TO SOLVE THIS TYPE OF PROBLEM.
Example :
In this example, i have created an object t2 in the same class.but,in actual case, that object is created in some other program called test2. And test2 doesnt know abt the class(test1) being used.And is being determined at runtime (i.e., dynamical).
class test1
int i = 10;
String s;
public static void main(String a[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException
test1 t = new test1();
System.out.println("I = " + t.i);
System.out.println("Class Name = " + t.getClass().getName());
t.s = t.getClass().getName();
Object t2 = t.getClass().newInstance();
System.out.println("t2 I = " + ((test1)t2).i);
System.out.println("t2 Class Name = " + t2.getClass().getName());If you have no idea what members the class could have in compile time, then how can you set them in runtime?
I think you should give another though to your OO design... -
I have an attribute CategoryId in my VO of type oracle.jbo.domain.Number. I am trying to use the expression of Boolean item in JHS as #{row.CategoryId != 4}
Here is the generated JSF code:
<af:column id="s141NewItem3Col" noWrap="true" width="100"
rowHeader="false">
<f:facet name="header">
<af:outputLabel value="CAtIDDeq4" showRequired="false"
id="ol18"/>
</f:facet>
<af:inputText id="s141NewItem3"
value="#{row.CategoryId != 4}"
label="CAtIDDeq4" required="false"
readOnly="#{((pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn']))) or ((!pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn'])))}"></af:inputText>
</af:column>I am getting the run time exception as "Can not convert 4 of type class oracle.jbo.domain.Number to class java.lang.Long"
I am wondering how the row.CategoryId is treated as Long?. PLease advise. Also, will I be able to use type casting expressions in J Headstart/JSF Expression Language?
Thanks, PradeepI am trying to set disabled property of an item SubCategory dynamically based on CategoryId value. I guess the transient attribute will not work for newly created records as the transient attribute will be null for newly created records before save is performed. However, the expression #{row.bindings.CategoryId.attributeValue.value== 4 ? false : true} is working fine. row.bindings.CategoryId.attributeValue seem to be returning Long and, row.bindings.CategoryId.attributeValue.value might be returning a Number.
-
Hi Team,
Could any one explain me about Type casting used in oops abap and in what circumstances it is
used with an example.
Regards,
Pradeep P.Hi,
Hi,
Go to ABAPDOCU tcode and see example programs in abap objects section, you will find separate programs for upcasting and downcasting .
Up-Cast (Widening Cast)
Variables of the type reference to superclass can also refer to subclass instances at runtime.
If you assign a subclass reference to a superclass reference, this ensures that
all components that can be accessed syntactically after the cast assignment are
actually available in the instance. The subclass always contains at least the same
components as the superclass. After all, the name and the signature of redefined
methods are identical.
The user can therefore address the subclass instance in the same way as the
superclass instance. However, he/she is restricted to using only the inherited
components.
In this example, after the assignment, the methods GET_MAKE, GET_COUNT,
DISPLAY_ATTRIBUTES, SET_ATTRIBUTES and ESTIMATE_FUEL of the
instance LCL_TRUCK can only be accessed using the reference R_VEHICLE.
If there are any restrictions regarding visibility, they are left unchanged. It is not
possible to access the specific components from the class LCL_TRUCK of the
instance (GET_CARGO in the above example) using the reference R_VEHICLE.
The view is thus usually narrowed (or at least unchanged). That is why we
describe this type of assignment of reference variables as up-cast. There is a
switch from a view of several components to a view of a few components. As
the target variable can accept more dynamic types in comparison to the source
variable, this assignment is also called Widening Cast
Static and Dynamic Types of References
A reference variable always has two types at runtime: static and dynamic.
In the example, LCL_VEHICLE is the static type of the variable R_VEHICLE.
Depending on the cast assignment, the dynamic type is either LCL_BUS or
LCL_TRUCK. In the ABAP Debugger, the dynamic type is specified in the form
of the following object display.
Down-cast (Narrowing Cast)
Variables of the type reference to superclass can also refer to subclass instances
at runtime. You may now want to copy such a reference (back) to a suitable
variable of the type reference to subclass.
If you want to assign a superclass reference to a subclass reference, you must
use the down-cast assignment operator MOVE ... ?TO ... or its short form
?=. Otherwise, you would get a message stating that it is not certain that all
components that can be accessed syntactically after the cast assignment are
actually available in the instance. As a rule, the subclass class contains more
components than the superclass.
After assigning this type of reference (back) to a subclass reference to the
implementing class, clients are no longer limited to inherited components: In the
example given here, all components of the LCL_TRUCK instance can be accessed
(again) after the assignment using the reference R_TRUCK2.
The view is thus usually widened (or at least unchanged). That is why we describe
this type of assignment of reference variables as down-cast. There is a switch
from a view of a few components to a view of more components. As the target
variable can accept less dynamic types after the assignment, this assignment is
also called Narrowing Cast
Reward if helpfull,
Naresh. -
Any way to search for casts in java source code?
Anyone know of a decent way to search your java source files to find all the casts?
I ended up doing a simple text search for
" = ("(quote marks not included) which works for my code because I am strict about writing my casts with spaces like
String s = (String) iterator.next();Unfortunately, the above search has all kinds of problems with both false positives and negatives. It picks up lots of irrelevant lines like
int index = (number > 0) ? 0 : 1;as well as misses casts that appear nested inside expressions like
((String) iter.next()).charAt(...)I suppose that one could do a regular expression search for any pair of open and close parens which bound non-blank text, but that would pick up even more non-cast expressions in typical java code.
I think that the only way to properly do this is to have a tool which understands java syntax.
Anyone know of an IDE which will do this? Does IntelliJ or Netbeans support this kind of search?
In case you are wondering why I am interested in this, it is because I am refactoring some code to fully use generics, and searching for casts is one source of identifying candidates for genericity.cliffblob wrote:
Better late than never?Yes!
cliffblob wrote:
...The answer I found to ID unnecessary casts was, using Eclipse IDE, In compiler error and warning preferences to warn on unnecessary casts.Thanks for pointing IDEs out. I just opened IntelliJ, and going back to at least version 7.04 (maybe earlier) they have an inspection for "Redundant type cast".
cliffblob wrote:
I would still be interested to know if there is a way to identify casts in general in your source, perhaps now four years later there is a way?The only solutions that I can think of are either a complicated regex search, or you must use some tool like an IDE that understand Java syntax and can determine if a cast is happening. -
Help needed in data type casting
I have a java program which will receive data and its type in the String format. During program execution, the data in the String data has to be converted into the respective data type and assigned to a variable of that data type so that it could be used in the program. Programmer may not know the type of data that the value has to be converted into.
I really got struck up with this. This is a RMI application and one process node is sending the data to another node in the String format and the type of data it should get converted into so that it can be converted into the respective type and used for computation.
Can you understand what I am asking for ....if you can pls help and it is highly appreciatedI dont know whether i ahve expressed it correctly
look at this code
dataPacket sendtoNode = send.senDatatoNode(inputReq);
String recnodnum = sendtoNode.nodeNum;
String recvarnum = sendtoNode.varNum;
String recvartype = sendtoNode.dataType;
String recvalvalue = sendtoNode.dataVal;
int num; int type;
double result;
// here in this case the result variable type is double
if (recvartype.equals("int")){
type = 1;
result = Integer.parseInt(recvalvalue); will pose problem
else
if (recvartype.equals("double")){
type = 2;
result = Double.parseDouble(recvalvalue);
else
if(recvartype.equals("float")){
type =3;
result = Float.parseFloat(recvalvalue); will pose problem
else
if(recvartype.equals("Boolean")){
if ((recvalvalue.equals("true")) || (recvalvalue.equals("TRUE")))
type = 4;
result = Boolean.parseBoolean(recvalvalue); will pose problem
else
if(recvartype.equals("char")){
type = 5;
result = (char)recvalvalue; will pose problem
else
if(recvartype.equals("String")){
type = 6;
result = recvalvalue; will pose problem
else
if(recvartype.equals("byte")){
type = 7;
result = Byte.parseByte(recvalvalue); will pose problem
else
if(recvartype.equals("long")){
type = 8;
result = Long.parseLong(recvalvalue); will pose problem
else
if(recvartype.equals("short")){
type = 9;
result = Short.parseShort(recvalvalue); will pose problem
//forvarval varvalue = new forvarval();
//varvalue.forvarval(recvartype, recvalvalue);
// this has to be done after sorting the problem of type casting string result = recvalvalue;
//result = value; //<this will surely give me a problem as i m assigning string to double>??
send.host(result);
System.out.println("result received and the result is " +recvalvalue );
now i need to assign the converted string in to a variable and use in the compuation ..thts where the challenge n not in teh conversion process... -
Does anybody know how to get (or Cast) a Java Object returned from a Java method call ?
Example:
<cfset someList = object1.method1(someString, JavaCast("float",someNumber),...)>
This method returns a list of Java object of type "Object2". ie. it returns List<Object2>
Now I attempted to loop thru each objects from the returned list, and invoke some method on them, using code similar to below,
<cfset var="#someList[index]#"/>
but ColdFusion does not seem to understand the object "var" as Java "Object2". Is there any way I can cast the "var" to "Object2"?
Thanks in advance.
Xiaoling"var" is a reserved keyword! You can initialize variables with "var" in the beginning of a component, but do not use it as a variables name:
<cfset var someVar = "#someList[index]#"> -
Hi Guys,
I am pretty new at generics and have started reading all material available online. Shown below is the API that I am using
package api;
public interface CS<C extends MyConfig> extends S {
package api;
public interface MyConfig {
package api;
public interface MySession {
public <C extends MyConfig, T extends ResourceContainer<? extends C>>
T createContainer(CS<C> aPredefinedConfig);
package api;
public interface NC extends ResourceContainer<NCC> {
package api;
public interface NCC extends MyConfig {
package api;
import java.io.Serializable;
public interface ResourceContainer <T extends MyConfig> extends Serializable {
package api;
public interface S {
public abstract boolean equals(Object other);
public abstract int hashCode();
public abstract String toString();
}And below is my implementation
package impl;
import api.NC;
public class NCImpl implements NC {
package impl;
import api.CS;
import api.MyConfig;
import api.MySession;
import api.ResourceContainer;
public class MySessionImpl implements MySession {
public <C extends MyConfig, T extends ResourceContainer<? extends C>> T createContainer(
CS<C> predefinedConfig) {
NCImpl ncimpl = new NCImpl();
return ncimpl; //Error Type mismatch: cannot convert from NCImpl to T
}As shown above I get error at line 'return ncimpl' But NCImpl implements the NC which extends ResourceContainer<NCC> so shouldn't it be capable of Type casting to T or I am missing something.
Thanks a lot for your response in advancecontinuation of stack trace .................
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Compilation failure
/home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
found : impl.NCImpl
required: T
/home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
found : impl.NCImpl
required: T
[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.BuildFailureException: Compilation failure
/home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
found : impl.NCImpl
required: T
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:579)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:499)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:478)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:330)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:291)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:287)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.plugin.CompilationFailureException: Compilation failure
/home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
found : impl.NCImpl
required: T
at org.apache.maven.plugin.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:516)
at org.apache.maven.plugin.CompilerMojo.execute(CompilerMojo.java:114)
at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:451)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:558)
... 16 more
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5 seconds
[INFO] Finished at: Thu Feb 12 10:39:43 IST 2009
[INFO] Final Memory: 14M/81M
[INFO] ------------------------------------------------------------------------
[abhayani@localhost GenericsTest]$
Maybe you are looking for
-
Second graphics card for p-series laptop?
I have a satellite P-Series laptop with an Nvidia GeForce 740M graphics card and wanted to install another graphics card onto it. Would this be possible? Are these laptops expandable?
-
Multiple view state best practice for IOS packaged app - Tabbed view or blank template?
TabbedViewNavigatorApplication or plain Application? I have an iPad app that has a fairly complex main view. Has lots of view state changes. Before a user can get to that main view, however, they have to go through two other screens: 1. Authentica
-
MTOM support in OSB11g to send the mails
Hi, We have come with a generic email service based on the requirements using OSB11g. Since the furture direction is only using the MTOM we are using MTOM feature to send the attachments. But when we enable the MTOM in osb proxy service we are unable
-
Hi, I would like to generate print preview of all the fields in the form dynamically when the user clicks a button. How do I make a pop up PDF form when the user clicks a button. The reason for not going for Adobe's print functionality is that I have
-
Speedgrade crashes every time I use split into clips function as part of scene detection.
Speedgrade CC (latest version) crashes every time I use split into clips function as part of scene detection. I can use the keyframe function fine, but if i split it into clips it crashes 9 out of 10 times... so to get the job done i simply keep reop