Runtime Casting

I have a hashtable with different objects types inside it. Since they are swing objects, all of them are handled by a single function.
Enumeration enum = hash.keys();
while( enum.hasMoreElements() )
     // The key is always a String, so a hard cast is acceptable
     String key = (String)enum.nextElement();
     Object val = hash.get(key);
     // Try Use Reflection to retrieve the class
     Class interfaceClass = Class.forName(val);    // ??
     panel.add( (interfaceClass)val  );            // ??
}What I would like to do is cast these objects without having to write a switch statment to delimit hard casts. The following code works, but since I have to hard code the answers is *obviously a poor way to do it.
Enumeration enum = hash.keys();
while( enum.hasMoreElements() )
     String key = (String)enum.nextElement();
     Object val = hash.get(key);
     // Use Reflection to retrieve the class
     Class interfaceClass = val.getClass();
     String className = interfaceClass.getName();
     if( className.endsWith("JButton") )
          panel.add( (JButton)val  );
     else if( className.endsWith("JCheckBox") )
          panel.add( (JCheckBox)val  );
}Any help with the dynamic casting problem would be appericated.
~Kullgen
(PS, After searching the forums for a solution, I find that when people ask this question they are invariably flamed for poor design. This is not a design question, but just a problem with having to use the clunky java swing. IMHO Swing was very poorly designed, and thus leaves itself open to the problems above. I want this to be a post about runtime casting, not about design)

Since all the has elements are Swing componets they are all instances
of java.awt.Component. So simply cast to that and everything will be
just fine and dandy. No need for lots of switch statements.
For example:
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Kullgen1
     public static void main(String[] argv)
          Hashtable hash= new Hashtable();
          hash.put("Button", new JButton("Button"));
          hash.put("Label", new JLabel("Label"));
          hash.put("TextField", new JTextField("TextField"));
          JFrame frame= new JFrame();
          JPanel panel= new JPanel(new GridLayout(0,1));
          frame.getContentPane().add(panel);
          Iterator components= hash.values().iterator();
          while(components.hasNext())
               panel.add((Component) components.next());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setVisible(true);
}

Similar Messages

  • Runtime casting problems

    The following code gives me runtime casting problems:
    package edu.columbia.law.markup.test;
    import java.util.*;
    public class A {
       protected static Hashtable hash = null;
       static {
          hash = new Hashtable ();
          hash.put ("one", "value 1");
          hash.put ("two", "value 2");
       public static void main (String args []) {
           A a = new A ();
           String keys [] = a.keys ();
           for (int i = 0; i < keys.length; i++) {
               System.out.println (keys );
    public String [] keys () {
    return (String []) hash.keySet ().toArray ();
    The output on my console is:
    java.lang.ClassCastException: [Ljava.lang.Object;
            at edu.columbia.law.markup.test.A.keys(A.java:37)
            at edu.columbia.law.markup.test.A.main(A.java:29)I can not understand why is it a problem for JVM to cast?
    Any ideas?
    Thanks,
    Alex.

    return (String []) hash.keySet ().toArray ();This form of toArray returns an Object[] reference to an Object[] object. You cannot cast a reference to an Object[] object to a String[] reference for the same reason that you cannot cast a reference to a Object object to a String reference.
    You must use the alternate form of toArray instead:
    return (String []) hash.keySet ().toArray (new String[0]);This will return an Object[] reference to a String[] object, and this reference can be cast to a String[] reference.

  • Will generics implementation eliminate runtime casting?

    Before generics, one must explicitly cast when pulling out of an iterator. For example:
    List l = ...
    for(Iterator i = l.iterator(); i.hasNext();) {
    doSomethingWithInteger((Integer)l.next());
    Now with generics, we won't have to explicitly cast the return value of the iterator's .next() method:
    List<Integer> l = ...
    for(Iterator i = l.iterator(); i.hasNext();) {
    doSomethingWithInteger(l.next());
    However, form what I've seen of decompiled code compiled with the beta version of the generics compiler, there is still implicit casting going on. The return value of Iterator.next() is still being casted to an Integer. And runtime casting like this has actual instructions to be executed, not just syntactic sugar. It seems silly to me, though, since everything in the List is an Integer, there should be no need to explicitly cast it.
    So will the addition of generics not be able to eliminate this overhead? Why was this decided?

    It actually turns out that the runtime casts are extremely cheap to do, because modern superscalars typically have plenty of extra functional units and branch prediction on the cast is extremely accurate (all the casts inserted by JSR-14 are always true, so the branches always predict correctly).
    But even though they have a negligible performance cost, they do bloat the binary. The NextGen proposal
    http://doi.acm.org/10.1145/286936.286958
    was always the "future" solution to this. It's the second step of the implementation. The first step is JSR-14.

  • Unable to cast object of type InfoObject to DestinationPlugin

    I have created a web application to show the list of scheduled reports and with their destination Info using Business objects sdk. Locally on my computer i am able to show all the reports and the Ftp information. But when i move this application to QA server the application returns an error with a message.
    "Unable to cast object of type 'CrystalDecisions.Enterprise.InfoObject' to type 'CrystalDecisions.Enterprise.DestinationPlugin"
    I have noticed that the returned type of Object by the query on QA server is of type "InfoObject" and on localbox "CrystalDecisions.Enterprise.Dest.Ftp"
    Query
    Select * from ci_systemobjects where SI_NAME= ''", "CrystalEnterprise.Ftp"
    Assemblies required by application are registered in the GAC with same version and same public token
    Please let me know if anyone has a answer for this casting exception.

    Snippet:
    Dim ftp As New Ftp(infoObject.PluginInterface)
    Dim ftpOptions As New FtpOptions(ftp.ScheduleOptions)
    You wouldn't be doing a direct runtime cast.
    Sincerely,
    Ted Ueda

  • Array casting: ClassCastException

    import java.util.Vector;
    public class X
    public static void main(String args[])
         //first part
    String [] array = {"1","2", "3"};
    Object [] objs = array;
    array = (String[])objs;
    for( int i =0 ; i < array.length; i++)
    System.out.println(array);
         //second part
    Vector v = new Vector();
    v.add("1");
    v.add("2");
    v.add("3");
    objs = v.toArray();
    array = (String[])objs;
    for( int i =0 ; i < array.length; i++)
    System.out.println(array[i]);
    Why does the first part work properly but the second cause ClassCastException? Even if an array was instantiated as Object[] in toArray method casting MUST be ok. I work with an instances in array but not with array. An array only contains an objects I work with. It's only technical structure! Why does it cause ClassCastException?

    >
    Yes. I know it. The point is WHY it was done in this
    way? What can I do with the type of array? NONE. The
    actual information is CONTAINED in array. So array
    is only technical structure. I can't derive it, it has
    no virtual mechanisms. The actual objects I need are
    stored in array. The type of them is important. It
    looks like miss of language structure.
    The basic question here is a fundamental part of polymorphism - you cannot cast an Object into one that it is not.
    Object a = new Object();
    String b = (String) a;That code will also compile, but it is just as incorrect as your code. The problem is that "a" will never be a String. There may be ways to convert it into a String, but the object a will always be of type "Object" and never extend String, so it cannot be cast.
    Similarly, an array of type Object[] will always be of type Object[]. It cannot be cast to String[], because it will never have String[] as a superclass, if you will. The rules for working with arrays are exactly the same as working with the object which is the base type of the array.
    In order to be able to do a cast from Object[] to String[], there would have to be a runtime check which would ensure that every element in the Object[] was, in fact, a String. But the cast check in the compiler is just looking up the extends and implements chains. If you want to implement a runtime cast, Java basically leaves that up to you.
    And as has been mentioned, they do let you provide the array to be used as well.

  • "unchecked call to put(K, V)..."

    Hi, I was till recently using this passage -
    public static final Hashtable map = new Hashtable();
    static {
    map.put(TextAttribute.FONT, new Font("Serif", Font.PLAIN, 14));
    to enable me to pass map into an AttributedString constructor.
    On upgrading to j2se 1.5, I now get this warning from javac: "unchecked call to put(K, V) as a member of the raw type java.util.Hashtable"
    Can anyone explain to me what this means and what to do? (Can't find any of these words in the API).
    Thanks
    Tom

    try here:
    http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html
    In Java 1.5 you can type what goes into the collection to stay away from runtime casting errors.

  • Insert Excel information to Access Table, cf error

    I am trying to create a file upload that will allow me to use a .csv file, to insert the data into an access database. I have the code written, but right now, it's giving me an error and I can't figure out what I'm doing wrong, this is my first time doing this, so any and all help would be greatly appreciated.
    This is my code to read the .csv file.:
    <cftry>
    <cffile action="DELETE" file="#FORM.attachment_1#"/>
    <cfcatch>
    <!--- File delete error. --->
    </cfcatch>
    </cftry>
    <cfelse>
    <!--- no errors with the file upload so lets upload it--->
    <cffile action="upload"
                     filefield="attachment_1"
                     result="myResult"
                     accept = ""
                     destination="f:\websites\211562Fe3\uploads\"
                     nameconflict="Makeunique">
    <cfset svrFile = "#myResult.ServerDirectory#"&"\"&"#myResult.ServerFile#"/>
    <!--- get and read the CSV-TXT file --->
    <cffile action="read" file="#svrFile#" variable="csvfile">
    <!--- loop through the CSV-TXT file on line breaks and insert into database --->
    <cfloop index="index" list="#csvfile#" delimiters="#chr(10)##chr(13)#">
        <cfquery name="importcsv" datasource="#APPLICATION.dataSource#">
             INSERT INTO employees (siteID,empstatus,empfirstname,empmiddlename,emplastname,empnickname,emplocation,empgende r,empdob,empdoh,empee)
             VALUES
                      ('#listgetAt('#index#',1, ',')#',
                       '#listgetAt('#index#',2, ',')#',
                       '#listgetAt('#index#',3, ',')#',
                       '#listgetAt('#index#',4, ',')#',
                       '#listgetAt('#index#',5, ',')#',
                       '#listgetAt('#index#',6, ',')#',
                       '#listgetAt('#index#',7, ',')#',
                       '#listgetAt('#index#',8, ',')#',
                       '#listgetAt('#index#',9, ',')#',
                       '#listgetAt('#index#',10, ',')#',
                       '#listgetAt('#index#',11, ',')#'
       </cfquery>
    </cfloop>
    <cffile action="DELETE" file="#svrFile#"/>
    <!--- use a simple database query to check the results of the import - dumping query to screen --->
    <cfquery name="rscsvdemo" datasource="#APPLICATION.dataSource#">
             SELECT * FROM csvdemo
    </cfquery>
    <cfdump var="#employees#">
    </cfif>
    The error is in the insert query, I have all my columns named the same ad the database table and in the same order, I also formatted each cell in the .csv to be the same as the database.
    This is the error:
    Error Executing Database Query.
    [Macromedia][SequeLink JDBC Driver][ODBC Socket][Microsoft][ODBC  Microsoft Access Driver] Data type mismatch in criteria expression.
    The error occurred in  C:\websites\211562fe3\partners\cfm\csvUploadAction.cfm: line 60
    58 :                    '#listgetAt('#index#',9, ',')#',
    59 :                    '#listgetAt('#index#',10, ',')#',
    60 :                    '#listgetAt('#index#',11, ',')#' 
    61 :                   )
    62 :    </cfquery>
    Thank you

    I changed my code a little.. now I get an error about converting a date.. so I must be on the right track.... Can you help me straiten this out?
    This is my "new" code:
    <cftry>
    <cffile action="DELETE" file="#FORM.attachment_1#"/>
    <cfcatch>
    <!--- File delete error. --->
    </cfcatch>
    </cftry>
    <cfelse>
    <!--- no errors with the file upload so lets upload it--->
    <cffile action="upload"
                     filefield="attachment_1"
                     result="myResult"
                     accept = ""
                     destination="c:\websites\211562Fe3\uploads\"
                     nameconflict="Makeunique">
    <cfset svrFile = "#myResult.ServerDirectory#"&"\"&"#myResult.ServerFile#"/>
    <!--- get and read the CSV-TXT file --->
    <cffile action="read" file="#svrFile#" variable="csvfile">
    <!--- loop through the CSV-TXT file on line breaks and insert into database --->
    <cfloop index="i" list="#csvfile#" delimiters="#chr(10)##chr(13)#">
        <cfquery name="importcsv" datasource="#APPLICATION.dataSource#">
             INSERT INTO employees (siteID,empstatus,empfirstname,empmiddlename,emplastname,empnickname,emplocation,empgende r,empdob,empdoh,empee)
             VALUES
                      (<CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#trim(listgetAt(i,1))#">,
                        <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,2)#">,
                        <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,3)#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#trim(listgetAt(i,4))#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,5)#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,6)#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,7)#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,8)#">,
                     <CFQUERYPARAM CFSQLTYPE="CF_SQL_DATE" VALUE="#listgetAt(i,9)#">,
                     <CFQUERYPARAM CFSQLTYPE="CF_SQL_DATE" VALUE="#listgetAt(i,9)#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,9)#">
       </cfquery>
    </cfloop>
    <cffile action="DELETE" file="#svrFile#"/>
    <!--- use a simple database query to check the results of the import - dumping query to screen --->
    <cfquery name="rscsvdemo" datasource="#APPLICATION.dataSource#">
             SELECT * FROM employees
    </cfquery>
    <cfdump var="#employees#">
    </cfif>
    I'm not sure it's totally correct.. but the error is different!
    This is the error:
    The cause of this output exception was that:  coldfusion.runtime.Cast$DateStringConversionException: The value empdob  cannot be converted to a date..
    The error occurred inf :\websites\211562fe3\partners\cfm\csvUploadAction.cfm: line 58
    56 :                  <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar"  VALUE="#listgetAt(i,7)#">,
    57 :                  <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar"  VALUE="#listgetAt(i,8)#">,
    58 :                  <CFQUERYPARAM CFSQLTYPE="CF_SQL_DATE"  VALUE="#listgetAt(i,9)#">,
    59 :                  <CFQUERYPARAM CFSQLTYPE="CF_SQL_DATE"  VALUE="#listgetAt(i,9)#">,
    60 :                  <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar"  VALUE="#listgetAt(i,9)#">
    Also I can make my .csv file available for you if you need it. Also, the date is being inseted in this format: 3/3/1952

  • Flash.utils.Proxy Question

    hi list,
    I am trying to extend flash.utils.Proxy so that I can
    intercept calls
    made on an innerObject and provide cross cutting
    services/advices like
    writing to a log or caching... (AOP...)
    The big problem is that the user of the innerObject needs to
    be aware
    of the ProxyClass otherwise - calls will not be intercepted.
    for example:
    a proxy factory class looks like this-
    public class ProxyFactory
    private var _target:*;
    public function ProxyFactory(target:*){
    _target = target;
    public function GetProxy():*{
    var proxy:AOPProxy = new AOPProxy(_target);
    return (proxy);
    and the usage:
    var person:Person = factory.GetProxy();
    this will produce a runtime casting exception!!
    the fix is to do something like this:
    var person:AOPProxy = factory.GetProxy();
    or even -
    var person:* = factory.GetProxy();
    BUT - this is bad because the user of the factory is aware of
    the
    proxy AND he loose code assist... he cannot see the
    properties of the
    Person Class.
    Does anybody know of a better way (maybe creating runtime
    code
    generated proxies??- code emission...)
    Thanks,
    Chen Bekor
    Software Architect.

    quote:
    it looks a bit strange for a developer to have to instantiate
    objects via a factory to get some AOP functionality. Doesn't this
    tie you down to the specific AOP framework you are using, or am I
    missing something?
    I agree - it was just an example - the question is does
    flash.utils.Proxy is the proper direction to provide AOP in
    ActionScript3?
    quote:
    Have you checked out the AOP framework of as2lib (
    http://www.as2lib.org/)?
    yes I did - its ActionScript2 - and it use deprecated API in
    ActionScript3
    - I'm trying to write my own AOP implementation to
    Flex...
    - do you have any idea?

  • AIR SQLite timezone question (JavaScript)

    SQLite stores dates in UTC, which is great, but when I fetch the value, the resulting date object is incorrectly offset. Hopefully I'm missing something obvious and someone can point it out. Here's what I'm doing:
    CREATE TABLE myTable ("id" INTEGER PRIMARY KEY ,"created" DATE);
    INSERT INTO myTable (id,created) VALUES (1,DATETIME('NOW'));
    SELECT id,created FROM myTable WHERE id=1;
    My expectation is that the INSERT will store the current date/time adjusted to UTC. Because the AIR runtime casts date values to JavaScript date objects, my expectation is that the SELECT would give me back a valid date object, from which I could display either UTC or local time information. And it almost does.
    Suppose 'NOW' is 11:42:23 AM Pacific Time (GMT-8). I would expect the time information from toString() on the resulting date object to print something like "11:42:23 GMT-0800" but instead, I'm getting "19:42:23 GMT-0800". Clearly, it's a timezone issue because minutes and seconds look good. It's like AIR (or SQLite) is assuming that the value "11:42:23" is already UTC when inserting, and when AIR creates the resulting date object, it's applying the 8 hour timezone offset.
    I tried the solution posted here, which is to modify the INSERT as follows.
    INSERT INTO myTable (id,created) VALUES (1,DATETIME('NOW','localtime'));
    That works, but I don't want to store these values as local times, I want to store them as UTC and display them as local times. Meaning I should be able to store "11:42:23" in the Pacific timezone, and if I change to Eastern, I expect that value to be displayed as "14:42:43". When I use this solution, toString prints "11:42:23 GMT-0500".

    Update: Based on this topic on Stack Overflow, I tried changing the value in the insert from "DATETIME('NOW')" with a parameter:
    stmt.parameters[":created"] = new window.runtime.Date();
    (Aside: it's kind of annoying that AIR does not support JS dates, I'd like to see that change.)
    Anyway, this still doesn't solve the original problem. It works just like using DATETIME('NOW','localtime'). If the value goes in at 1:54pm PST, and I change the timezone to EST and read the value, it displays as "1:54pm EST", when I would expect it to be "4:54pm EST".
    Any advice is appreciated. Thanks!

  • Autumated code transformation from J2SE 1.5 to J2SE 1.4

    Hi colleagues !
    Is the subject of my topic possible ?

    Don't think so. What do you do with classes that didn't exist in 1.4?I think it's possible in theory: implement all those new classes using
    Java 1.4 and change the imports accordingly. A bigger (syntactical)
    problem is that pooped up for-loop, varargs and generics. Annotations
    can simply be ignored. Removal of generics can cause a lot of
    explicit runtime casts but you had to cast in Java 1.4 anyway.
    Would it be worth all the trouble? Nah, don't think so.
    kind regards,
    Jos

  • ORM CFC Wizard shows up blank

    I'm trying out the ORM CFC Wizard from a table in my RDS Dataview. When I do this I get the option to select where I want the CFC created and the checkbox to create the CFC in script.
    Once I click OK, the next screen is blank.
    I've searched through the forums and found some suggestions of turning off debugging and renaming all references to "Framework" to "framework".
    I've made sure debugging is turned off and went through and made sure all references to "Framework" are all lowercase with no luck.
    Has anyone been able to fix this issue with success?
    I'm running CF 9 on JBOSS 5.2 on OS X 10.6.3 if that helps any. RDS works fine as I can see my datasources.
    One thing I noticed, if I refresh the ORM Wizard screen it does generate a premature end of file error on the XML. But this error doesn't happen on the first try.
    Thanks,
    Ben

    Hello,
    Did you ever resolve this issue...I am having the same problem.
    Mac OS X 10.6
    Coldfusion builder 1 with update 1
    When I right-click "Reload" I get a big dump:
    coldfusion.xml.XmlProcessException: An error occured while Parsing an XML document. at coldfusion.xml.XmlProcessor.parse(XmlProcessor.java:183) at coldfusion.runtime.Cast._Xml(Cast.java:1345) at coldfusion.tagext.validation.CFTypeValidatorFactory$CFXMLValidator.validate(CFTypeValidat orFactory.java:425) at coldfusion.runtime.UDFMethod.validateValueType(UDFMethod.java:182) at coldfusion.runtime.UDFMethod._validateArg(UDFMethod.java:1072) at coldfusion.runtime.UDFMethod._validateArg(UDFMethod.java:1089) at cfRequestProcessor2ecfc1904329852$funcPARSEREQUEST.runFunction(/Library/WebServer/Documen ts/Adobe CFC Generator/handlers/framework/RequestProcessor.cfc:14) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:472) at coldfusion.filter.SilentFilter.invoke(SilentFilter.java:47) at coldfusion.runtime.UDFMethod$ReturnTypeFilter.invoke(UDFMethod.java:405) at coldfusion.runtime.UDFMethod$ArgumentCollectionFilter.invoke(UDFMethod.java:368) at coldfusion.filter.FunctionAccessFilter.invoke(FunctionAccessFilter.java:55) at coldfusion.runtime.UDFMethod.runFilterChain(UDFMethod.java:321) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:517) at coldfusion.runtime.TemplateProxy.invoke(TemplateProxy.java:495) at coldfusion.runtime.TemplateProxy.invoke(TemplateProxy.java:354) at coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:2301) at coldfusion.tagext.lang.InvokeTag.doEndTag(InvokeTag.java:375) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2723) at cfORMManager2ecfc1990215907$funcLOADTABLES.runFunction(/Library/WebServer/Documents/Adobe CFC Generator/handlers/framework/ORMManager.cfc:265) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:472) at coldfusion.runtime.UDFMethod$ReturnTypeFilter.invoke(UDFMethod.java:405) at coldfusion.runtime.UDFMethod$ArgumentCollectionFilter.invoke(UDFMethod.java:368) at coldfusion.filter.FunctionAccessFilter.invoke(FunctionAccessFilter.java:55) at coldfusion.runtime.UDFMethod.runFilterChain(UDFMethod.java:321) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:517) at coldfusion.runtime.TemplateProxy.invoke(TemplateProxy.java:495) at coldfusion.runtime.TemplateProxy.invoke(TemplateProxy.java:354) at coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:2301) at coldfusion.tagext.lang.InvokeTag.doEndTag(InvokeTag.java:382) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2723) at cflayoutpage2ecfm1151129293.runPage(/Library/WebServer/Documents/Adobe CFC Generator/handlers/layoutpage.cfm:37) at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:231) at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:416) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2722) at cfApplication2ecfc1209604170$funcONREQUEST.runFunction(/Library/WebServer/Documents/Adobe CFC Generator/handlers/Application.cfc:84) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:472) at coldfusion.runtime.UDFMethod$ReturnTypeFilter.invoke(UDFMethod.java:405) at coldfusion.runtime.UDFMethod$ArgumentCollectionFilter.invoke(UDFMethod.java:368) at coldfusion.filter.FunctionAccessFilter.invoke(FunctionAccessFilter.java:55) at coldfusion.runtime.UDFMethod.runFilterChain(UDFMethod.java:321) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:220) at coldfusion.runtime.TemplateProxy.invoke(TemplateProxy.java:490) at coldfusion.runtime.TemplateProxy.invoke(TemplateProxy.java:336) at coldfusion.runtime.AppEventInvoker.invoke(AppEventInvoker.java:88) at coldfusion.runtime.AppEventInvoker.onRequest(AppEventInvoker.java:280) at coldfusion.filter.ApplicationFilter.invoke(ApplicationFilter.java:338) at coldfusion.filter.RequestMonitorFilter.invoke(RequestMonitorFilter.java:48) at coldfusion.filter.MonitoringFilter.invoke(MonitoringFilter.java:40) at coldfusion.filter.PathFilter.invoke(PathFilter.java:87) at coldfusion.filter.LicenseFilter.invoke(LicenseFilter.java:27) at coldfusion.filter.ExceptionFilter.invoke(ExceptionFilter.java:70) at coldfusion.filter.ClientScopePersistenceFilter.invoke(ClientScopePersistenceFilter.java:2 8) at coldfusion.filter.BrowserFilter.invoke(BrowserFilter.java:38) at coldfusion.filter.NoCacheFilter.invoke(NoCacheFilter.java:46) at coldfusion.filter.GlobalsFilter.invoke(GlobalsFilter.java:38) at coldfusion.filter.DatasourceFilter.invoke(DatasourceFilter.java:22) at coldfusion.filter.CachingFilter.invoke(CachingFilter.java:53) at coldfusion.CfmServlet.service(CfmServlet.java:200) at coldfusion.bootstrap.BootstrapServlet.service(BootstrapServlet.java:89) at jrun.servlet.FilterChain.doFilter(FilterChain.java:86) at coldfusion.monitor.event.MonitoringServletFilter.doFilter(MonitoringServletFilter.java:42 ) at coldfusion.bootstrap.BootstrapFilter.doFilter(BootstrapFilter.java:46) at jrun.servlet.FilterChain.doFilter(FilterChain.java:94) at jrun.servlet.FilterChain.service(FilterChain.java:101) at jrun.servlet.ServletInvoker.invoke(ServletInvoker.java:106) at jrun.servlet.JRunInvokerChain.invokeNext(JRunInvokerChain.java:42) at jrun.servlet.JRunRequestDispatcher.invoke(JRunRequestDispatcher.java:286) at jrun.servlet.ServletEngineService.dispatch(ServletEngineService.java:543) at jrun.servlet.jrpp.JRunProxyService.invokeRunnable(JRunProxyService.java:203) at jrunx.scheduler.ThreadPool$DownstreamMetrics.invokeRunnable(ThreadPool.java:320) at jrunx.scheduler.ThreadPool$ThreadThrottle.invokeRunnable(ThreadPool.java:428) at jrunx.scheduler.ThreadPool$UpstreamMetrics.invokeRunnable(ThreadPool.java:266) at jrunx.scheduler.WorkerThread.run(WorkerThread.java:66)

  • Object variables

    Is there a way to find the variable names in an object when you know the object type but not, obviously, the variables in the object?

    Fair enough. I don't really see why it is backwards
    though.If you think about it carefully, you'll realise that the kind of "runtime cast" you're after would be completely useless even if it was possible. If it was possible, then once you'd performed the cast, what would you expect to be able to do - i.e., what would the next few lines of code look like? and would they make any sense? The answer is no, and I say that without any doubt whatsoever: If you don't know the type of the object at compile-time (not necessarily the type, but at least one of its superclasses, or an interface that it implements), then you can't call its methods or access its fields anyway (except via reflection, but then there would be no need to cast the reference), so a "runtime cast" wouldn't help. If you do know the type, then just use a standard cast.
    What I am trying to do is write a class/method
    which can handle a variety of object types rather than
    writing one for every one of the types I want to
    handle. And what do you want to be able to do with them?
    Somebody already suggested a common interface type for the objects - this is almost certainly the way to go, but you haven't told us enough about what you want to do for us to be able to help you too much. Perhaps you could post a little pseudo-code? Then we might be able to poast back some Java code that demonstrates how to solve your problem
    If I am missing the point then I bow to your
    greater knowledge and shall redirect my question to a
    more appropriate forum.This is the appropriate forum isn't it?
    Search the forums for terms like "runtime cast" and "dynamic cast" - you'll probably find lots of threads about this (there's certainly been plenty in the past), and hopefully it'll help you to understand where your design is flawed.

  • Cf + postgres + array

    driver  of postgres included in coldfusion8 (postgresql-8.1-407.jdbc3.jar) has a bug in manager of array with pgsql 8.3
    i upgrade driver with postgresql-8.3-604.jdbc3.jar and now i have a problem with array without elements...
    look at the image. seems that array obkect is modified...
    the code is :
    <cfoutput query="q">
    <cfloop from="1" to="#ArrayLen(PST_CATEGORIES_ID)#" index="i">
    #q.PST_CATEGORIES_ID[currentrow][i]#<br>
    </cfloop>
    </cfoutput>
    now, looping over this array, i've received this error:
    Element 1 is undefined in a Java object of type class coldfusion.runtime.Cast$1.
    how can skip the value if the element not exist? (undefined array element)
    many thanks!
    Rob

    > Maybe I can manipulate cookies in the same way, tho I'm
    thinking sandbox rules
    > probably will prevent that.
    Before the notion of AJAX was around, Jim Davis wrote an
    essay on how to do
    async comms with a GIF and a cookie.
    http://www.depressedpress.com/Content/Development/JavaScript/Articles/GIFAsPipe/Index.cfm
    This covers the cookie manipulation you mention.
    > Obviously JS and CF can not communicate in real time but
    assuming they can not
    > communicate is incorrect.
    Well I think the point is that they cannot communicate
    *directly*: they
    need to use HTTP. Just like you and I can't just talk to each
    other
    directly: we need a forum.
    Really a lot of people on these forums seem to think "CF is a
    computer
    language which has something to do with making my web page do
    stuff...
    JavaScript is a computer language which has something to do
    with making my
    web page do stuff. That's pretty much the same: they must
    just
    intrinsically be able to play with each other's code". And
    they don't seem
    to "get" the whole client / server thing. I think from your
    earlier posts
    in this thread it would be fair enough for people to be
    saying "well...
    no... it doesn't work like that". I don't think anyone was
    assuming it's
    not possible, I think they might have been giving the
    "Client/Server 101"
    answer, before moving on to the "Client/Server 102: why that
    is the answer"
    spiel. Quite possibly they could have skipped to the latter,
    in this case.
    Adam

  • How to cast an object to a class known only at runtime

    I have a HashMap with key as a class name and value as the instance of that class. When I do a 'get' on it with the class name as the key, what I get back is a generic java.lang.Object. I want to cast this generic object to the class to which it belongs. But I don't know the class at compile time. It would be available only at runtime. And I need to invoke methods on the instance of this specifc class.
    I'm not aware of the ways to do it. Could anybody suggest/guide me how to do it? I would really appreciate.
    Thanks a lot in advance.

    Thanks all for the prompt replies. I am using
    reflection and so a generic object is fine, I guess.
    But a general question (curiosity) specific to your
    comment - extraordinarily generic...
    I understand there's definitely some overhead of
    reflection. So is it advisable to go for interface
    instead of reflection?
    Thanks.Arguments for interfaces rather than reflection...
    Major benefit at run-time:
    Invoking a method using reflection takes more than 20 times as long without using a JIT compiler (using the -Xint option of Java 1.3.0 on WinNT)... Unable to tell with the JIT compiler, since the method used for testing was simple enough to inline - which resulted in an unrealistic 100x speed difference.
    The above tests do not include the overhead of exception handling, nor for locating the method to be executed - ie, in both the simple method invocation and reflective method invocations, the exact method was known at compile time and so there is no "locative" logic in these timings.
    Major benefit at compile-time:
    Compile-time type safety! If you are looking for a method doSomething, and you typo it to doSoemthing, if you are using direct method invocation this will be identified at compile time. If you are using reflection, it will compile successfully and throw a MethodNotFoundException at run time.
    Similarly, direct method invocation offers compile-time checking of arguments, result types and expected exceptions, which all need to be dealt with at runtime if using reflection.
    Personal and professional recommendation:
    If there is any common theme to the objects you're storing in your hashtable, wrap that into an interface that defines a clear way to access expected functionality. This leaves implementations of the interface (The objects you will store in the hashtable) to map the interface methods to the required functionality implementation, in whatever manner they deem appropriate (Hopefully efficiently :-)
    If this is feasible, you will find it will produce a result that performs better and is more maintainable. If the interface is designed well, it should also be just as extensible as if you used reflection.

  • Dynamic cast at runtime (Here we go again! )

    Hy folks,
    today I read so many entries about dynamic casting. But no one maps to my problem. For a lot of them individual alternatives were found. And so I hope...
    Ok, what's my problem?
    here simplified:
    I have a HashMap with couples of SwingComponents and StringArray[3].
    The SwingComponents are stored as Objects (they are all JComponents).
    The StringArray comprised "the exact ClassName" (like "JButton" or "JPanel"),
    "the method, who would be called" (like "addItemListener")
    and "the ListenerName" (like "MouseMotionListener" or "ActionListener")
    At compiletime I don't know, what JCommponent gets which Listener.
    So a JPanel could add an ItemListener, another JPanel could add
    a MouseListener and an ActionListener.
    I get the description of the GUI not until runtime.
    The 'instanceof'-resolution is not acceptable, because there are above 50 listener. If I write such a class, I would write weeks for it, and it will be enormous.
    Now, my question
    I get the class of the Listenertype by
    Class c=Class.forName(stringArray[2]);
    and the method I'll call
    java.lang.reflect.Method method=component.getClass().getDeclaredMethod(s[1],classArrayOfTheParameter[]); //the parameter is not important here
    And I have a class, who implements all required ListenerInterfaces: EHP
    Now I wish something like this
    method.invoke((JPanel)jcomponent,(c)EHP);
    Is there anybode, who can give me an alternative resolution
    without instanceof or switch-case ?
    Greatings egosum

    I see, your right. Thanks. This problem is been solved.
    But a second problem is, that jcomponent can be every Swing-Object.
    I get the swing-component as Object from the HashMap . And I know
    what it is exactly by a String.
    What I need here is
    method.invoke(("SwingType")swingcomponentObject,Object[] args);
    I know, that this doesn't exist. Here my next question
    Can I take an other structure than HashMap, where the return value
    is a safety type (and not an Object). Or there are some other hints
    about similar problems and there resolutions?
    I don't like to write 50 (or even more than 50) "instanceOf"-instructions or "equal"-queries. And I'm not really interested in the whole set of java swing elements existing.
    I appreciate all the help I can get.
    With regards egosum

Maybe you are looking for

  • How can I set up a Macbook to wake up at a certain time for backing up?

    My wife objects strenuously to Time Capsule (wireless) backups so I finally set it to once a day, starting at 7 pm. You would think that would work but NO, runs too long and even next morning to finish. We are backing up only documents, mail, safari,

  • What is the difference in Interactive reports and Drill down reports?

    What is the difference in Interactive reports and Drill down reports? Are they same?

  • Third Party Software installed by 7.5

    During the upgrade to 7.5 Skype for Windows desktop, I only realized that by not paying attention to the defaulted checkboxes at each step of the Skype installer, that I was installing one of eight third party products.  Each of the uninstallers for

  • LOB locater from Java?

    I seem to be having a problem with getting a CLOB from a Java stored procedure. I have public class TheJava { public static CLOB getData(int arg){. . . which is specified by FUNCTION getClobData(a IN NUMBER)RETURN CLOB AS LANGUAGE JAVA NAME 'TheJava.

  • TV Tuner or Video capture device for MBP

    I'm wondering if there is a device usb or expresscard34 that can allow me to watch cable TV or just a composite video input device that can be used with a cable box. I know there must be lots of devices for PPC Macs but which ones actually work on MB