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_silly

There 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.

Similar Messages

  • I can't open or save file with Java Web Start

    Hi,
    i can't open or save file with Java Web Start:
    import java.io.*;
    import java.util.*;
    public class MetaDataFileCreator {
    public String fileNameSpace = null;
    public String fileName = null;
    protected Properties file = null;
    public MetaDataFileCreator(String fileNameSpace, String fileName) {
    this.fileNameSpace = fileNameSpace;
    this.fileName = fileName;
    public void createMetaDataFile() {
    try {
    System.out.println("file METADATA");
    ClassLoader cl = this.getClass().getClassLoader();
    String nameFileMetaData = fileNameSpace + fileName + ".txt";
    FileOutputStream fileOS = new FileOutputStream(cl.getResource(nameFileMetaData).getFile());
    file = new Properties();
    file.setProperty("aaaaa", "aaaa");
    file.store(fileOS, "");
    fileOS.close();
    } catch (Exception e) {
    System.out.println("Error writing metadata-file: " + e);
    System.exit(1);
    e.printStackTrace();
    I have try also to open a file like this:
    ClassLoader cl = this.getClass().getClassLoader();
    file.load(cl.getResourceAsStream(nameFile));
    also like this:
    try {
    fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
    fss = (FileSaveService)ServiceManager.lookup("javax.jnlp.FileSaveService");
    } catch (UnavailableServiceException e) {
    fss = null;
    fos = null;
    System.out.println("Error with JNLP");
    System.exit(1);
    if (fss != null && fos != null) {
    try {
    // get a FileContents object to work with from the
    // FileOpenService
    FileContents fc = fos.openFileDialog(null, null);
    //FileContents newfc2 = fss.saveAsFileDialog(null, null, fc);
    // get the OutputStream and write the file back out
    if (fc.canWrite()) {
    // don't append
    os = fc.getOutputStream(false);
    } catch (Exception e) {
    e.printStackTrace();
    also like this:
    File f = new File((System.getProperty("user.home")+"x.txt").toString());
    FileOutputStream fileX = new FileOutputStream(f);
    OutputX = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fileX, "UTF8")));
    OutputX.println(....
    but it doesn't work with Java Web Start.
    Can someone help me?
    How can I open or save file?
    thank you.
    Sebastiano

    Did you specify <all-permissions/> in your JNLP file? Did you sign your code? What error are you getting?

  • Can we give a class name by java keyword ?

    can we give a class name by java keyword ?e. can we create a class call "for" / "if" anyhow ? Is there some way to create such kind of classes .. Is is possible with some other java like language.. & if there is any language & how one can embed the script/language in java ..
    Please let me know
    Regards

    can we give a class name by java keyword ?e. can we
    create a class call "for" / "if" anyhow ? Is there
    some way to create such kind of classes .. Is is
    possible with some other java like language.. & if
    there is any language & how one can embed the
    script/language in java ..
    I give up - why would you want to?

  • NewBie Question: Can you make a website completely with Java?

    Greetings my new Fellow Java programmers. My name is Jason and I am a computer programmer and web developer. I am verse in the following:
    1. HTML/XHTML
    2. CSS
    3. Asp.net
    4. VB.Net
    5. SQL
    I want to expand my skills to include:
    1.JAVA
    2. Action Script
    3. Java Script
    4. Ajax
    I have always wanted to learn Java and now I think it is the right time. So my question is can you create a site complete with Java or have a majority of the site functions and look attributed to Java? Is it similar to creating a site with vb.net and asp.net which utilizes html as well? Please explain. I am eager to learn this language. Thank you.
    -RomDog
    ...ROOOOOF!

    RomDog wrote:
    Is it similar to creating a site with vb.net and asp.net which utilizes html as well? Please explain. I am eager to learn this language. Thank you.
    I find it strange that you have to ask this. Of course the end result will be HTML/XHTML, that's what the browsers want. I would think that if you know the .NET side of web development, these concepts (client/server technologies) should already be clear to you.
    The short answer is yes it is possible. However if you want to learn Ajax/Javascript/Actionscript, I would learn those technologies before you learn Java web development as they are completely unrelated. You know that Javascript is not Java, right? You can implement javascript/Ajax in your .NET web applications already.
    Before you want to learn Java web development, learn Java. Seriously, learn basic Java first. It will be a great deal harder (and ultimately a lot more frustrating) to jump directly into the web development side of Java without knowing any of the basics. One of the biggest differences between .NET and Java platforms is that Microsoft basically holds your hand when it comes to making decision about which APIs to use and how to attack a problem; Java leaves you to the wolves to select from a gigantic amount of APIs and tools available that can each solve a problem in their very own way. Freedom is great, but it can be very daunting when you are just beginning.
    So before you even think about web development, I suggest you explore the java tutorial and see if you can get to grips with the language and the tool set.
    [http://java.sun.com/docs/books/tutorial/|http://java.sun.com/docs/books/tutorial/]
    When you are comfortable with the Java language and you are sure that Java web/enterprise development is still something for you, then come back and ask the question again.

  • How can I compact a MSAccess database with java?

    Hi.
    I have a question (Please Help!!!):
    How can I compact a MSAccess database with java-jdbc? Is it posible?
    Thanks

    MS Access database has a max length limitation of 2.14GB for Access 2000( 1.07G for Access 97), and won't recycle basically space for update/delete sql so tha it's a good idea to use MS Access database for program, which need update/delete frequent ly data. The programmers of HXTT Access(www.hxtt.net) are writing code for CREATE TABLE/DATABASE sql now. If you need a pure Java solution for PACK TABLE/DATABSE urgently in your project, you should send such a requirement to the Support page of www.hxtt.net so that they can schedule complementing such a fucntion. Otherwise, you should pack your databae manually or visit C++ code for Compact an Access Database Programmatically at
    http://www.codeguru.com/Cpp/data/mfc_database/microsoftaccess/article.php/c4327/ , or use Easy Microsoft Access MDB MDE Compactor at http://www.easyhr.com.au/software/easy_mdb_mde_compactor.htm.

  • Can  i use SLE4428 smart card with java card developmentkit 2.1.2

    Can i use SLE4428 smart card with java card developmentkit 2.1.2
    plz reply

    No. SLE4428 is memory card and not Java Card.

  • Dynamic class casting.

    Hi Friends,
    How do I cast an object dynamically ?
    Here I made a sample example for what I need exactly.
    java.lang.String str = "sample";
    java.lang.Object obj = str;
    Class cls = obj.getClass();
    java.lang.String tmpStr = (cls)obj; // this is an error.
    Instead of casting like (java.lang.String), I wanted to replace "(java.lang.String)" with an variable.
    Any ideas??
    Thanks,
    SK.

    Doesn't make sense to me at all why you think you'd
    need that. You already know you want it to be a
    java.lang.String, because you coded:
    java.lang.String tmpStr = (cls)obj;
    Certainly you and the compiler have to know beforehand
    the object type you need to cast to, so why the fuss?Hi,
    I typed wrongly in my org. note. Sorry about that.
    Actual code snippet looks like this.
    java.lang.String str = "sample";
    java.lang.Object obj = str;
    Class cls = obj.getClass();
    cls tmpStr = (cls)obj; // this is giving me an error.
    I wanted to cast that field dynamically, because upfront I dont know the type of the object.
    In the above example, just for the example sake, I selected a data type "String". Actually I need to cast it based on the type of the object at runtime.
    Thanks,
    SK.

  • Question  about dynamic class loading with thread built in

    Hi ,
    I am trying to load a class with a thread built in from the network.
    I write my network classloader, convert the class to a byte array and transmit over the network using socket. This step seems fine but when I tried to load the class at the receiver, some exception happens,"
    the reported exception is that :
    Exception in thread "Thread-2" java.lang.NoClassDefFoundError: SampleProject/Application$1
    my class name is "SampleProject . Application", the $1 I think it may refers to the thread built in the "Application".
    Could any one give me some hint for how to dynamic load such class file with thread built in over the network?
    Thank you!
    Best Regards,
    Song Guo

    Exception in thread "Thread-2"
    java.lang.NoClassDefFoundError:
    SampleProject/Application$1That means that the receiving end can't find an anonymous inner class which you have in the Application class. (The anonymous clas is given the synthetic name 1). Check your bin/classes folder you will have a class there with the name Application$1.class
    Kaj

  • Dynamic class casting during runtime

    I'm reading parameters for my application from the configuration file. Then in the code I should dynamically during the runtime make class cast:
    (instead of having String in the code, I should cast the object to the class that was
    defined in the configuration file.)
    String tmp = (String) object;
    Could somebody provide an example how can I do this? I have understood I could use reflection API for this problem.

    I am not sure that I understand what you are asking correctly, but it might be something that bothered me some time ago.
    My problem was that I wrote names of Classes (as Stings) into a file, and later wanted to be able to initialize a specific object of the class based on String names that were read from that file.(sorry if this is confusing).
    I was programing a Chess simulator. All figures were subclasses of the class Figure, and were named Peon, Queen...)
    I wanted to make a new Peon object, for every "Peon" String that was read from the file, and to make an new Queen object for every "Queen" in the file and so on.
    I used something like this:
    String objectName = in.readUTF(); //or some other way to get a String
    Figure f = (Figure) Class.forName(objectName).newInstance(); Class.forName(String name) returns a object of class Class that represents all objects of type name.
    And invoking .newInstance() gives you a new object of the class that is being represented by the object of class Class that you invoked .newInstance() on.
    Sorry - migth be confusing again but i think it is correct.
    This call to .newInstance() calls the default no-argument constructor...
    There is no way to call a argument containing constructor with .newInstance()

  • Can't create dynamic html elements with jsp????? important

    Hi All,
    I am having problem creating dynamic html elements with jsp tags, i have tried to use EL and java scriplet, both of them don't work.
    i am trying to create dynamic menu in my "rightMenu.jspf", based on, if user has logged in or not.
    some like this!
    <jsp:if test ="${validUser == null}">
    some simple text menu here
    </jsp:if>
    but it is not working. it simply loading all and images with in statement, regardless of whether user has logged in or not. i think some how if statement is not working properly.
    "validUser" is a session bean, which is not creating at this point, it will created when user will log in successfully. and also this session bean does not exist at the page, where i am trying to check that .
    Is there any way to create dynamic values in jsp. It is really important, is there any body who help me in this matter. i would be really grateful.
    zaman

    hi jaspre,
    thanks for replying me. you know what, is it not something wrong with web.xml file. i remember once, i deleted some from there, a property with "*.jsp". i can't remember what exactly was it though.
    all if statements works on files ending with extension ".jsp" but don't work only on with extension ".jspf". there must be to do with this.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <servlet>
    <servlet-name>ValidateServlet</servlet-name>
    <servlet-class>ValidateServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ValidateServlet</servlet-name>
    <url-pattern>/ValidateServlet</url-pattern>
    </servlet-mapping>
    <servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
    <init-param>
    <param-name>debug</param-name>
    <param-value>true</param-value>
    </init-param>
    <init-param>
    <param-name>pollAndCometEnabled</param-name>
    <param-value>true</param-value>
    </init-param>
    </servlet>
    <servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>
    <session-config>
    <session-timeout>
    30
    </session-timeout>
    </session-config>
    <welcome-file-list>
         <welcome-file>
    main.jsp
    </welcome-file>
    </welcome-file-list>
    </web-app>
    if any one can figure it out. i would be grateful.
    zaman

  • Dynamic class loading with Webstart

    Hello !
    //within the jar-file at the webstart-directory
    public interface MyFrame{
    public void createFrame();
    //within the jar-file dynamically downloaded
    public class MyExtFrame extends JFrame implements MyFrame{
    String className = "MyExtFrame";
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    JarClassLoader jarLoader = new JarClassLoader (cl, jarFile));
    /* Load the class from the jar file and resolve it. */
    Class c = jarLoader.loadClass (className, true);
    /* Create an instance of the class.
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof MyFrame){
    // Yep, lets call a method we know about. */
    MyFrame client=(MyFrame) o;
    //call a class-method (here creates the whole gui-object at once)
    client.createFrame();
    This is the code i'm using and i've encountered following problem, if i put this code into an application without webstart, anything works fine, but with webstart i'll get a: java.lang.NoClassDefFoundError
    Then i've put the MyFrame-classes into the downloaded jar-file, but this won't work either, i'll get a ClassCastException.
    What do i have to do, to become it working ?
    Thanks for any conclusions and help.
    Michael

    Finally i've found out myself, i've read some postings in this forum and put them all together, so that my webstart-application finally works the way i want...
    That was the topic:
    Downloading a jar-file and starting a class from this jar-file within a webstart application (dynamic class loading).
    I'll post my final solution for this problem, may be it would be useful in future for anyone else.
    //grant all permissions on the clientside
    Policy.setPolicy( new Policy() {
    public PermissionCollection getPermissions(CodeSource codesource) {
    Permissions perms = new Permissions();
    perms.add(new AllPermission());
    return(perms);
    public void refresh(){
    //get the current classloader
    ClassLoader cl = MyLoadedClass.class.getClassLoader();
    //create a new url-classloader while using the current classloader
    URL[] urls = new URL[1];
    File f = new File(new String(jarName));
    urls[0] = f.toURL();
    URLClassLoader ul = new URLClassLoader(urls, cl);
    //load a class from jarfile
    Class c = ul.loadClass(new String(className));
    //get an object from loaded class
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof KnownInterface){
    // Yep, lets call a method we know about. */
    KnownInterface client = (KnownInterface) o;
    client.doAnything();

  • Can't find xml within jar with java webstart

    I use Jasper Reports,I am reading a xml file in my application.
    The code I use to read this xml file is:
    JasperCompileManager.compileReportToFile("xmlfile.xml","jasperfile.jasper");
    When I run this code in JBuilder it run fine.
    But when I compile the classes and this xml to my jar file,sign it and then try to run it in java Webstart.It tells me that it can not find the path.
    What is wrong?

    I don't know Jasper Reports, so I may be wrong here.
    A file inside a .jar file is not a file on the filesystem, and cannot be accessed with java.io file-related classes. You should use ClassLoader.getResource() to get an inputstream reading from it.

  • How can i create a printable format with Java

    Hello....
    First, my english is not good, but this is possibly my last hope!! I have a program with EJB's, JBoos and a MySql database! The program shows the data from the database and you can do something with these data. Now my problem to print this data. I want create a formular which will be print! I've treid ut with docbook and the javax.print library.
    The first problem is: with linux docbook works very fine. I transform the sgml-file in many formats with "db2pdf or db2ps......"
    but the javax.print library don't find any printservice! I've J2EE 1.4.1 where the bug canceld from the earlier version!
    So the next problem is: with windows the javax.print library works fine! I find the printservices and can print *.ps or *.pdf! But i can't transform the sgml-file in Postscipt or PDF!
    I've tried to solve this problem for two weeks now, but without any success.
    Now my Question is: have somebody experiences with this problem and can help me or is there another possibility to solve my problem!!!
    Thanks
    FIPS

    seems to be important!
    k, do this.
    1. ur english is wonderful for a programmer, are u US :)
    2. i will suggest u create an XML file.
    then u can print it and do the hell with it.
    so : java ==> XML ==> what ever u want.
    and if u can also what ever u want ==> XML ==> java.
    this works also fine.

  • Dynamic Class Loading with interface

    Hello
    I would appreciate any help on the following problem.
    I need to load all classes in a particular directory and its subdirectories (top directory is known but not in the classpath) which implement a predefined interface. At the moment I am using a lot of reflection to accomplish this and believe it can be avoided somehow using the fact that I know these classes have to implement a predefined interface.
    At the moment, I am searching through the directory and subdirectory, loading all names of classes into a vector using a custom URLClassloader, and then load all classes in the vector into modulecontainers to populate a defaultmutabletree which is displayed on the gui.
    I'm sure that knowing the interface means there's a more straightforward way.
    Thanks in advance.

    Finally i've found out myself, i've read some postings in this forum and put them all together, so that my webstart-application finally works the way i want...
    That was the topic:
    Downloading a jar-file and starting a class from this jar-file within a webstart application (dynamic class loading).
    I'll post my final solution for this problem, may be it would be useful in future for anyone else.
    //grant all permissions on the clientside
    Policy.setPolicy( new Policy() {
    public PermissionCollection getPermissions(CodeSource codesource) {
    Permissions perms = new Permissions();
    perms.add(new AllPermission());
    return(perms);
    public void refresh(){
    //get the current classloader
    ClassLoader cl = MyLoadedClass.class.getClassLoader();
    //create a new url-classloader while using the current classloader
    URL[] urls = new URL[1];
    File f = new File(new String(jarName));
    urls[0] = f.toURL();
    URLClassLoader ul = new URLClassLoader(urls, cl);
    //load a class from jarfile
    Class c = ul.loadClass(new String(className));
    //get an object from loaded class
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof KnownInterface){
    // Yep, lets call a method we know about. */
    KnownInterface client = (KnownInterface) o;
    client.doAnything();

  • Can I develop a driver mouse with Java?

    Hi,
    Can you tell me, if I can develop a driver mouse with Java and if not why and with which programming software?
    And do you have a web site or forum reference about driver mouse?
    Best regards,
    Dimnet2000

    Aren't you all a little too hasty with your NOs?
    If the task is to develop a standard plugged-in mouse driver you see and use everyday and that loads together with the bootup process of Linux, Windows... the answer propably is "No" or "better not".
    Other than that... You can draw on the screen and you can communicate with the Serial Port. I think you could very well build your own mouse driver for a non standard Mouse to make it work in all Java applications. If you don't need 100% platform independancy you might think about building modules to trigger OS-Events via JNI.
    For standard use this might not seem a sensible thing to do, but imagine if you are in some way handicapped and need a very special mouse that you want to carry around and use across several platforms without compiling and instaling drivers everywhere...

Maybe you are looking for

  • Difference b/w Read and SynchRead in FTP Adapter

    Hi All, I wanted to know the difference b/w read and synchread in FTPAdapter. Thanks.

  • " Load files into stack" Crach photoshop CC since the last update

    Hello, I have a probleme since the last photoshop's update... I don't don't know if it's the update is the reason for this crach but I'm used to working with this module often "Load files into stack" but this is the first time since Friday that is ph

  • Missing mouse clicks

    I have no idea why, but some mouseclicks are missing here. I can click stuff, but it doesn't do anything. This is maybe every 10th click. Any idea why this happens? Thanks

  • Framework order (blanket purchase order)

    Hi SAP consultants,                               can aanybody give me the senario of framework purchase order. i tried but it shows error " gr indicator is on " also it asks pricing conditions which you do not mention in it. best regards sandeep

  • MacBook Pro EFI Firmware Update 2.7: installed or not?

    I have MacBook Pro EFI Firmware Update 2.7 showing as installed on Mar 17, 2015 on my AppStore Updates page; it also shows up as installed on Mar 18, 2015 and yet Mavericks wants to install it again. I seriously doubt this update has been updated so