Dynamic Type casting
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.
Similar Messages
-
I want to cast an object to the class of another object whose class is not known statically.
Is there anyway to do it in a fully dynamic way ?
I tought about something like this :
Boolean b1 = new Boolean (true);
Boolean b2
// now suppose, I forget that b1 and b2 are Boolean
// But I remember that b1 can be casted into b2.
b2 = ( b1.getClass() ) b1;
But that just plain does not compile (which does not surprise me).
(It's just a silly example:I know b2=b1 & b2=(Boolean) b1 will both work in this case).You can find the type of an object at runtime using instanceof. In that way you can be sure to cast your object to the appropriate type, or generate an error if an object appears that you did not expect.
Hope this helps. -
Dynamic Type Checking... Is this possible?
I want to do a dynamic check for objec types in a datastructure. Something very similar to instanceof but using dynamic type parameter.
Syntactically speaking...
Instead of writing several methods like
public boolean isOfTypeXYZ( )
return ( this instanceof XYZ);
public boolean isOfTypeABC()
return ( this instanceof ABC);
...I want one single method like
public isOfType ( Class a_type)
return (this ***isoftype**** a_type);
}Where isoftype can somehow dynamically figure out if the object is of given type (class)
For those who want to know why I'd need this kind of contrived behaviour let me give a simple example (similar to my real issue).
Suppose I have a swing GUI application which has several laid out components like Containers, JPanels, JToolBars, JMenuItems, JButtons, JToggleButtons, JRadioButtons etc.
Now starting from the JFrame in this containment hierarchy, I want to find all instances of JButtons or say all instances of JRadioButtons or say all instances of JMenuItem or all instances of JComponents ...
I do not want to write a special method for each possible type I might encounter.
I want a more generic method like
searchComponents( Class a_class) that I can invoke by just changing its argument to convey the type.
Unfortunately getClassName() will not work as that gives the most derived type of the object. I want something very much like instanceof wherein I can check for an intermediate super class as well. (eg. All RadioButtons are AbstractButton and should return true for either type).
I tried to search for this in the forums but couldn't find something close to this. (There are several discussions about dynamic type casting which are different).Is this what you want?
searchComponents( Class a_class) {
// browse components
if (a_class.isInstance(component)) {
// do something
} -
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 -
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... -
Type casting or something of the sort
This might sound stupid, but I have a 25 character something such as:
1hjfu7y4$y*3fji2389561##k
and I do not know what type it is. It is not a string though, and that is the problem. Is there any sort of equivalent in AS to type casting of c++? Some sort of way to dynamically make this into a string?typeof():
trace(typeof(1hjfu7y4$y*3fji2389561##k)); -
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. -
Dynamic type conflict when assigning references - Dump
Hi All,
I am getting the dump "Dynamic type conflict when assigning references". In my application I have used a table control inside which I have input field, text view and text edit.
I guess the text edit is creating the issue. The error analysis report is below :
If anyone have any idea about the issue, please help.
Error analysis
An exception occurred that is explained in detail below.
The exception, which is assigned to class 'CX_SY_MOVE_CAST_ERROR', was not
caught in
procedure "IF_WDR_VIEW_ELEMENT_ADAPTER~SET_CONTENT" "(METHOD)", nor was it
propagated by a RAISING clause.
Since the caller of the procedure could not have anticipated that the
exception would occur, the current program is terminated.
The reason for the exception is:
It was tried to assign a reference to a rereference variable using the
'CAST' operation ('?=' or 'MOVE ?TO').
However, the current content of the source variable does not fit into
the target variable.
source type: "\CLASS-POOL=/1WDA/L0STANDARD\CLASS=CL_TEXT_EDIT"
target type: "\INTERFACE=/1WDA/VTABLE_CELL_EDITOR"
Information on where terminated
Termination occurred in the ABAP program "/1WDA/L3STANDARD==============CP" -
in "IF_WDR_VIEW_ELEMENT_ADAPTER~SET_CONTENT".
The main program was "SAPMHTTP ".
In the source code you have the termination point in line 2290
of the (Include) program "/1WDA/L3STANDARD==============CCIMP".
The termination is caused because exception "CX_SY_MOVE_CAST_ERROR" occurred in
procedure "IF_WDR_VIEW_ELEMENT_ADAPTER~SET_CONTENT" "(METHOD)", but it was
neither handled locally nor declared
in the RAISING clause of its signature.
The procedure is in program "/1WDA/L3STANDARD==============CP "; its source
code begins in line
2034 of the (Include program "/1WDA/L3STANDARD==============CCIMP ".
2265 if va__CONTENT_READONLY is bound and
2266 va__CONTENT_READONLY->IFUR_NW5__CONTROL~_IID <> ifur_nw5_invisible=>_iid_invisible.
2267 IFUR_NW5_SAPTABLECELL~HASCONTENT = abap_true.
2268 else.
2269 IFUR_NW5_SAPTABLECELL~HASCONTENT = abap_false.
2270 endif.
2271 endif.
2272
2273 * >> ProvideCONTENT
2274
2275 IF mv_CONTENT_READONLY <> va__CONTENT_READONLY.
2276 finalize_adapter( mv_CONTENT_READONLY ).
2277 mv_CONTENT_READONLY ?= va__CONTENT_READONLY.
2278 ENDIF.
2279
2280 * >> property-Aggregation mv_CONTENT_EDITABLE
2281 DATA va__CONTENT_EDITABLE TYPE REF TO /1WDA/VTABLE_CELL_EDITOR. "#EC NEEDED
2282 * >> UCA STANDARD|TABLE_CELL|CONTENT_EDITABLE
2283 data adp_uielement type ref to /1WDA/VUIELEMENT. "#EC NEEDED
2284 if mv_CONTENT_READONLY is not bound and
2285 mv_WD_TABLE_CELL_EDITOR is bound.
2286 va__CONTENT_EDITABLE ?= mv_CONTENT_EDITABLE.
2287 IF va__CONTENT_EDITABLE is bound and va__CONTENT_EDITABLE->m_view_element = mv_WD_TABLE_
2288 ELSE.
2289
>>>>> va__CONTENT_EDITABLE ?= create_by_view_element(
2291 view_element = mv_WD_TABLE_CELL_EDITOR
2292 parent = me
2293 ).Hi Everyone,
Thanks for your replies.
We raised an OSS call for the same and got the below response.
Dear Customer,
I've analized your actual problem and found out that you are using a notallowed combination of text edit as cell editor within table for
clasical Web Dynpro ABAP rendering. The text edit as cell editor work in701 releases when the lightspeed rendering is enabled. However in case
that you want to used
lightspeed rendering, I would suggest to upgrade on a higher
SP level than SP4 as for technical reason we can only deliver
corrections for Unified Rendering first from SP04. -
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 -
Is there a way to type cast an array of strings to numbers and back again?
I'm working on an application where I want to type cast a string like "power supply" into an array of existing numbers. Then sort the existing numbers, and finally convert the casted numbers back into a string so it can be read by the user. In the attachment, you can see my latest attempt with flatten/unflatten data and the 'convert string to byte array'. I can't seem to make this work. Any ideas?
Thanks - Paul
Attachments:
Paul's Temp scan for components.vi 56 KBOK, here's a quickie (LabVIEW 7.0).
Simply get the sort key from the 1D array, then build the table.
Message Edited by altenbach on 10-27-2006 01:34 PM
LabVIEW Champion . Do more with less code and in less time .
Attachments:
SortedTable.png 4 KB
SortedTable.vi 37 KB -
Hello,
How can I improve the XQuery below in order to obtain a minimised return to escape from both errors ORA-19279 and ORA-01706?
XQUERY for $book in fn:collection("oradb:/HR/TB_XML")//article let $cont := $book/bdy where $cont [ora:contains(text(), "(near((The,power,Love),10, TRUE))") > 0] return $book
ERROR:
ORA-19279: XPTY0004 - XQuery dynamic type mismatch: expected singleton sequence
- got multi-item sequence
XQUERY for $book in fn:collection("oradb:/HR/TB_XML")//article let $cont := $book/bdy where $cont [ora:contains(., "(near((The,power,Love),10, TRUE))") > 0] return $book//bdy
/*ERROR:
ORA-01706: user function result value was too large
Regards,
Daianebelow query works for 1 iteration . but for multiple sets i am getting following error .
When you want to present repeating groups in relational format, you have to extract the sequence of items in the main XQuery expression.
Each item is then passed to the COLUMNS clause to be further shredded into columns.
This should work as expected :
select x.*
from abc t
, xmltable(
xmlnamespaces(
default 'urn:swift:xsd:fin.970.2011'
, 'urn:swift:xsd:mtmsg.2011' as "ns0"
, '/ns0:FinMessage/ns0:Block4/Document/MT970/F61a/F61'
passing t.col1
columns F61ValueDate Varchar(40) Path 'ValueDate'
, DebitCreditMark Varchar(40) Path 'DebitCreditMark'
, Amount Varchar(40) Path 'Amount'
, TransactionType Varchar(40) Path 'TransactionType'
, IdentificationCode Varchar(40) Path 'IdentificationCode'
, ReferenceForTheAccountOwner Varchar(40) Path 'ReferenceForTheAccountOwner'
, SupplementaryDetails Varchar(40) Path 'SupplementaryDetails'
) x ; -
Is it possible to make a type cast in TestStand?
I've got the following problem.
I use a receive function which waits for an undefined package. (struct package).
The problem is i can't specify the module with the exaxt package.
Generally in C i define a Pointer and create enough buffer for it. Is it the same in TestStand?
Is it possible to make a type cast?
for example:
i've got these packages
struct packet;
struct data;
the function does not know which structure to receive.
err = receive(buffer,maxlen);
how do i specify the buffer variable?
can i create a type "void" with a String to have enough buffer.
and then to make a type cast, for example "Locals.dataobject = ((data)Locals.buffer)"
any ideas?
thx for helpUnfortunately there is no way to do type-casts in TestStand. What you could do is write a wrapper-dll in C, that has for example two parameters for both possible structs. The dll then takes one of the parameters, does the typecast and passes it on to your original dll.
From TestStand you can pass the struct(or better container in the "TestStand language") you want to use to the accoridng parameter of the wrapper-dll, leaving the other parameter empty or with some default-value.
Hope this helps!
André -
Hi All,
I get a short dump while generating a proxy in the backend.I give the package and the prefix and end up with a short dump.
Does any one know why this mught come up
"Dynamic type conflict during the assignment of references."
background: I imported a WSDl provided by legacy into PI and created service interfaces and then trying to generate a proxy class while i get this error.
Thanks.Hi Shyamsundar,
I will explain a problem that I usually see in some developments:
XSD originally: XSD transformed:
Root -> Root
Tag 1 type int -> Tag 1 type int
Tag2 type string -> Tag2 type string
Tag3 type any - Tag3 type string
Normally the tag3 should have a XML inside. Then the ABAPers have to construct the tag3 with a CDATA structure (CDATA is used to put in an XML tag more XML tags inside like a text and no to be interpreted).
Later in SAP PI you can extract the cdata with an XSL, you can find some examples in the SCN.
I don’t like to convert the whole XML in only one string tag, because this makes difficult the develop for the ABAPers, although the work inside the PI is very easy because with an XSL you can extract the whole message easily. (You can find some examples in the SCN)
Regards. -
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...
Maybe you are looking for
-
Is there standard report for planned and actual devlivery date?
Hi Guru, Could you help me to find standard report to compare planned delivery date in PO and actual delivery date (GR Posting date)? I wonder, Is there standard report for planned and actual delivery date? or I have to create a customizing report. T
-
HT2729 Itunes 11.1.5 no longer syncs with Apple TV Gen1
So I completed the upgrade to itunes 11.1.5 and now itunes does not recognize the apple TV's. Went to itune>preferences>and couldn't find the apple TV logo anymore. So reset the computer, airport, both apple TV's (1st gen) no joy there either. From t
-
TS4036 Gmail on my iPad & iPhone 5 password it incorrect and it is
I keep getting an error message: Cannot Get Mail, The user name and password for "Gmail" in incorrect. I changed my email 5 or 6 times, I deleted the account and re-added and still getting the error message on my iPad and iPhone 5
-
[CS4] Default new document profile
If I create a New Document Profile, how do I make it the default? I did it in CS3 but can't remember how. Michael mhphillips at gmail dot com
-
How do you Change Group Sort Direction using Report Client
It looks like there should be a sort direction property on the ISCRGroupOptions object but there is none. So how do you set the sort direction of the group?