Dynamic equivalent of the Java language CAST operator

Hello,
Here is what I want to do:
I have an Object that contain "something" (I don't know at compilation time). And I want to do this call:
Object myObject = new String("Hello");
myMethod (myObject);
having declared these:
public void myMethod (Integer dInt);
public void myMethod (String sString);
I want the second method to be called. How can I do that?
I'm looking for something like a dynamic equivalent of the Java language cast operator:
??? myMethod ( (myObject.getClass())myObject ); ???
or ?? myMethod ( (myObject.castTo(myObject.getClass()) ) ; ??
Thanks.

How 'bout using the instanceof operator?
Like this:
public myMethod(Object obj)
if (obj instanceof String)
//do String stuff
else if (obj instanceof Integer)
//do Integer stuff
}

Similar Messages

  • Some changes we need in the Java language

    Dear Java language makers,
    I'm actually coding a fairly complex program, and I'm facing several issues c++ does solve while Java doesn't handle them. I strongly wish these features could be included in next editions of the Java language, and I think I'm not the only one...
    1) Friend Class access
    Say I have a parser and a Data structure. The parser reads a file, and updates another class (being a data structure) as it parses line by line an input text file.
    I want my parser to fill up the data structure step by step, that is field after field, rather than using a constructor, because the information appears sequentialy in my text input file.
    Using a constructor to intitialize my data structure (rather than field by field access on a void object)would require me creating several variables in my parser for buffering the information, then create my object. This results in a loss of coding performance, and execution performance (spending time allocating and killing buffer values).
    On the other hand, I don't want these field values to be exposed to the users of my SDK, I want them to be accessed thru accessor methods.
    You would answer me : put both classes in the same package, and declare the fields of the data structure "protected", and accessors "public".
    Yes, that is a solution...but if you do really think Object Oriented, this sucks. Because a data structure and a parser are not the same thing, and I want to have them in separate packages.
    one being named myApp.Datasets, the other being named myApp.Parsers.
    And this can't be done with Java.
    If only I could declare in my data structure class the Parser class as a Friend Class, this would solve the issue and be CLEAN for Object Oriented programming !
    2) Operators
    This very annoying the Java language doesn't support operators
    Say you have a Vector3D class and you want to make a calculation :
    in c++, you can define operators for your class, and make a calculation like this :
    float a;
    Vector3D v1,v2,v3;
    //calculation
    v1 = v2 - v3 * a; //clean and easy to read
    Now in Java, not having operators, you have to deal with functions :
    float a;
    Vector3D v1,v2,v3, tmpv;
    v1=new Vector3D();
    tmpv=new Vector3D();
    //calculation
    tmpv.sub(v2,v3);
    tmpv.mul(a);
    v1=tmpv; //dirty and unreadable
    In Java you get 3 lines for a basic calculation. This is the way it's implemented in JAVA3D, and this is the best you can do in Java to my opinion.
    Just imagine how math code looks in java when you code a 3D Physics engine, regarding the previous exemple, and having to deal with matrices, vectors, quaternions...Well I give you a taste, a simple slice of the code :
    vtmp.cross(Airplane.vAngularVelocity,Element.vCGCoords); // rotational part
    vLocalVelocity = add(Airplane.vVelocityBody , vtmp);
    fLocalSpeed = magnitude(vLocalVelocity);
    if(fLocalSpeed > 1) vDragVector = div(negate(vLocalVelocity),fLocalSpeed);
    Vector3f v = new Vector3f();
    v.cross(vDragVector,Element[i].vNormal);
    vLiftVector.cross(v,vDragVector);
    tmp = magnitude(vLiftVector);
    vLiftVector=normalize(vLiftVector);
    v=new Vector3f(vDragVector);
    tmp = v.dot(Element[i].vNormal);
    Got it ? :)

    Because a data structure and a parser are not the same thing,
    and I want to have them in separate packages.Because a data structure and a parser are not the same thing, you should not jave them as the same type (class or interface), that is right. But this does not prevent us from putting them into the same package!
    java. lang.Integer and java.lang.String are not the same thing, but I am quite happy with them as classes in the same package.
    Put both classes in the same package, and declare the fields
    of the data structure "protected", and accessors "public".Protected access would allow access for inheriting classes as well. The default (package-wide) access would be better.

  • Which classes are inherent in the Java language?

    For some reason I just thought of the question this past 2AM.
    What classes are significant to the Java compiler? The list I thought of was:
    Object -- implements wait() and synchronized
    String -- all those convenience idioms we couldn't live without
    StringBuilder -- for String operators like "a" + var
    Integer, Long, Short, Char -- also for String operators like int i; String x = "abc" + i;
    Throwable -- needed for catch clause
    RuntimeException -- needed for implicit throw
    How about the following? Does javac need to know about these? Or are they all handled by the runtime base classes?
    Class
    Constructor
    Thread

    AlanObject wrote:
    jverd wrote:
    ErrorI've never run into this class before, but wouldn't the JVM and not the compiler be dealing with this?> I don't think it has to know about StringBuilder or StringBuffer, as the JLS does not require their use for string concatenation with +. It's just that most implementations do it that way.Good point.
    I don't doubt that in the creation of Java there were long discussions about this. They could have done away with the String-awareness of the language by forcing the use of direct methods but the usability issue won the day.
    Also, are there now classes implied in the use of the for-each statement (Collection?) and in enums (Enumeration?)That would be Iterable, a shiny new abstraction. And, by extension, Iterator. Both them and enums, though, are tricks of the compiler, syntactic sugar. There's no new bytecode for those mechanisms (as yet)

  • "Can you list me some features of the java language"(Interview question )

    Hi,
    This was a question I got yesterday in an interview, exactly as the interviewer said it.
    I listed off it's cross platform feature... what else would you have added?
    Question 2. He also looked for #2the differences between java and C++"

    It does if you put <sarcasm> tags in/Too easy, and that wasn't the point back then anyway. :)
    Look at this forum sometime and see how many people
    cram procedural code into a main and still call
    themselves "Java programmers". Yepp. I dare to say that I do much better design, yet I don't call myself a programmer, even though I get paid for coding.
    Java doesn't enforce
    it, either. There's no way to mandate O-O thought.Yes and no. IIRC (it's been a very long time, and I mostly did C, anyway), you can write C++ code without ever creating one class. You can't do that in Java. So It's be a bad OOD, but never a good structural design, as structural design doesn't know classes.

  • How do you get the Java API onto Computer

    Hi guys,
    Well I want to practice Java at home, but instead have been staying up late at night at the University's Computer Lab.
    I have downloaded the Forte for Java, but I don't need all the Graphics classes since my programming class is centered on Programming in the UNIX environment. Not too long ago, I purchased SuSE Linux which had the Java Language and the compiler. I successfully managed to dual boot an old computer with it. It was easy because SuSe Partitioned the drive for you if it had a WIN32 filesystem.
    My parents bought me a laptop and it came with Windows XP. I have ever since wanted to Dual Boot this system with Suse Linux, but can't because 1.) SuSe Linux doesn't partition the drive because Windows XP resides on a NTFS filesystem. 2.) I can't risk doing it myself because I have a lot of critcal information.
    It would be really neat to work in Linux to program, because then I could do some serious homework as well practice. Forte for Java I am not really knowledgeable of it. I can't get the editor to work and it doesn't feel like I am in UNIX at all which defeats the purpose of taking trying to succeed in this programming class.
    Could somebody help me with my woes on how to deal with these matters. How can I get SuSe Linux on my XP computer safely and if it can be done how do I use the Forte for Java.
    Thanks for all your support,
    mileinfive-serious about programming

    The first question: http://sdb.suse.de/en/sdb/html/dstark_linux_xp.html
    F4J will be the same on both operating systems.. what actually is your question regarding it?

  • Java language proposal #1

    The overhead of reference counting has led to a preference for mark-and-sweep garbage collection. But this has some obvious disadvantages as well. For example, creation of temporary objects chews up memory; this reduces performance due to having to search for unused objects during garbage collection. Although incremental garbage collection can spread the search cost evenly over time, this does not reduce the cost.
    It is evident that both reference counting and mark-and-sweep have their place. Although it is conceivable that the JVM could dynamically choose between the two for any given class, this seems difficult to implement.
    The Java language specification should allow the programmer to specify whether a class is reference counted or not. To maintain compatibility, reference counting could be specified by adding the "transient" keyword to the class declaration.

    It wasn't only the "overhead" of reference counting that led to the use of other methods of garbage collection. There was also the problem that circular references (which are very common) meant that islands of inter-reference could never be collected, leading to memory leaks. This is the case in Visual Basic, for example, and it's sometimes surprisingly difficult to write code to get circular references unlinked so that garbage collection can take place.
    There's also the problem that the existing method of garbage collection (which can be summarized as "Don't refer to it and it will go away") appears to be too complicated for many programmers to understand, leading them to voodoo coding styles to "get around it". So I don't support making it even more complicated.

  • Help needed in understanding the Java code.

    Hi All,
    I have recently started learning the Java language. I came across this example and had a problem in understanding the output of the program. I could follow that if the continue statement is present in the below program the output is "Found 9 p's in the string" . But if the continue statement is removed I could not understand why the output would be "Found 35 p's in the string" .Is it because of the spaces and characters other than p... (eter ier icked a eck of ickled eers)
    Example-----------------------
    The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count.
    class ContinueDemo {
    public static void main(String[] args) {
    String searchMe
    = "peter piper picked a " +
    "peck of pickled peppers";
    int max = searchMe.length();
    int numPs = 0;
    for (int i = 0; i < max; i++) {
    // interested only in p's
    if (searchMe.charAt(i) != 'p')
    continue;
    // process p's
    numPs++;
    System.out.println("Found " +
    numPs + " p's in the string.");
    Here is the output of this program:
    Found 9 p's in the string.
    To see this effect more clearly, try removing the continue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9.

    The answer is already in your example - "The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop."
    It unloads the current loop iteration when condition is matching. Loop is again starting from boolean expression inside loop declaration.
    Java Programming - java forum

  • Why public class name should be same as the java file name

    Hi,
    I would like to know, why public class name should be same as the its java file name. Iam in the process of finding the answer to this question. Can someone help me out in finding the explanation.
    Thanks in advance,
    Manoj

    This is a requirement of the Java reference compiler released by Sun. I have used compilers that did not require this, but most seem to follow the reference compiler (which is a very good idea). I am NOT sure if this is specified in the Java Language Specification. Some of the other regulars who are more familiar with the JLS than I may be able to tell you.
    ? {?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Java.io.NotSerializableException when trying to invoke java class Business Operations in studio

    According to WLI docs, the Java Class Business Operations doesn't need to be Serializeable.
    But somehow everytime I try to invoke the Busines Operations in studio, It always
    throws me exception : java.io.NotSerializableException. Is it something wrong
    with my Java Class ? The operation seems to be executed successfully but after
    that It looks like WLI is trying to serialize the object into database which can
    not be done because the Java Class is not serializeable. Changing the Java Class
    to serializeable is not an option since I don't have any control on this class.
    Please advise...
    regards,
    Martin

    According to WLI docs, the Java Class Business Operations doesn't need to be Serializeable.
    But somehow everytime I try to invoke the Busines Operations in studio, It always
    throws me exception : java.io.NotSerializableException. Is it something wrong
    with my Java Class ? The operation seems to be executed successfully but after
    that It looks like WLI is trying to serialize the object into database which can
    not be done because the Java Class is not serializeable. Changing the Java Class
    to serializeable is not an option since I don't have any control on this class.
    Please advise...
    regards,
    Martin

  • Java language enhancement for method and field

    similar to the way FooClass.class works in the language, i would like to see the following code constructs also supported by the java language:
    [FooClass.]someMethod.method
    [FooClass.]someField.field
    i thought i had read that something like this was coming in se 7, but i can't seem to find the "what's new in se 7" page. can anyone direct me to it?
    shackman01

    I haven't read anything about that, at all. but I hope it comes to be

  • Using the java jdk version as a conditional

    Hi,
    I have an method that I only want to occur for jdks over 1.4.2. Is there any easy way (handy API or something) of coding it so I can check what jdk the program is running on and then call or not call a method depending on this jdk being greater then jdk 1.4.2.
    Thanks,
    John

    no am refactoring an idl to java compiler and need to
    take into account changes in the Java Language
    Specification between JDK's, for instance certain
    things that were legal in early jdks are illegal now
    and therefore the compiler should not let java code
    be created if it will be illegal for the jdk in use.Could you give an example? The only one that I know of is that pre-1.4, you could use a method named assert(), and post-1.4 you can't. That's going to be a serious problem if it shows up in your IDL, but otherwise not something you need to worry about.
    I've found that the more likely case is that I want to use a version-N-specific library method, but still need to compile the code in a pre-version-N environment. In that case, reflection can help: at runtime, determine whether the method is available, and fall back to alternatives if it isn't.
    Also, is the JVM version that you're running your compiler on guaranteed to be the same one that runs the generated code? If not, then checking its version isn't going to help. Instead, you'll have to follow the lead of javac, and use "-source" flags on the command line.

  • Differences in the Java Editions

    Hi guys,
    Can anyone tell me the exact differences in the three editions of Java i.e, J2EE, J2SE and J2ME.
    Thanks.

    J2SE is the standard java edition, it contains the core APIs of the Java language.
    J2EE is the enterprise java edition,contains classes related to client/server programming such as web applications.
    J2ME is the micro edition, its used for developing applictaions for portable devices such as cell phones and PDAs.

  • Selling software programmed with Java language

    Hello,
    I'm new to the forums and currentley taking a Java programming class. A questions came up among the students....
    If I were to develop a program in the Java language and sell the Java-coded software for profit, what licenses would I need?

    You can license your own software in pretty much any way you want, it's yours after all.
    The only thing that you may have to consider that shipping the JRE with your software requires some additional thought, there are rules what you need to do for it to be allowed, but they aren't do hard to follow (Google for JRE redistribution license).

  • How to start learning java language?

    can any one advise me how to start with

    can any one advise me how to start withJVerd's post is great.
    Also there are some links I have compiled over the last few months along with others in this forum.
    Free Tutorials and Such
    Installation Notes - JDK 5.0 Microsoft Windows (32-bit)
    Your First Cup of Java
    The Java? Tutorial - A practical guide for programmers
    New to Java Center
    Java Programming Notes - Fred Swartz
    How To Think Like A Computer Scientist
    Introduction to Computer science using Java
    The Java Developers Almanac 1.4
    Object-Oriented Programming Concepts
    Object-oriented language basics
    Don't Fear the OOP
    Free Java Books
    Thinking in Java, by Bruce Eckel (Free online)
    Core Servlet Programming, by Merty Hall (Free Online)
    More Servlets, by Marty Hall (Free Online)
    A Java GUI Programmer's Primer
    Data Structures and Algorithms
    with Object-Oriented Design Patterns in Java, by Bruno R. Preiss
    Introduction to Programming Using Java, by David J. Eck
    Advanced Programming for the Java 2 Platform
    The Java Language Specification
    Books:
    Head First Java, by Bert Bates and Kathy Sierra
    Core Java, by Cay Horstmann and Gary Cornell
    Effective Java, by Joshua Bloch
    Also if you are in school, definatly take a intro to programming course.
    Have Fun,
    JJ

  • Java Language Specification error reports

    Well, I wanted to report a typo in The Java Language Specification, Third Edition (http://java.sun.com/docs/books/jls/download/langspec-3.0.pdf), so from http://java.sun.com/docs/books/jls/ I clicked on the "feedback form" link (which points at http://developers.sun.com/contact/feedback.jsp?&category=doc&mailsubject=Java%20Language%20Specification%20Feedback). This was redirected to http://www.oracle.com/technetwork/community/join/overview/index.html which offers no such feedback form. Consider this sort-of-broken link as the first problem I'm reporting.
    The second problem is in the aforementioned pdf, section 4.8 (Raw Types), page 58, where on can read:
    "The type of the member(s) of Inner depends on the type parameter of Outer. If Outer is raw, Inner must be treated as raw as well, as their is no valid binding for T."
    This should be instead:
    "The type of the member(s) of Inner depends on the type parameter of Outer. If Outer is raw, Inner must be treated as raw as well, as there is no valid binding for T."
    I think a forum category should be created for just this: error reports about the documentation (pdfs, APIs, support web pages).
    Edited by: Urhixidur on 2011-09-08 09:23

    Your intentions are admirable, but you are probably wasting your time. This is a forum for Java development related questions and 99.5% of the visitors are not related to Oracle at all. most likely nothing will be done with your information.
    I think a forum category should be created for just this: error reports about the documentation (pdfs, APIs, support web pages).It is a good idea actually, but such a thing would need very tight moderation and then there is still the question of how to arrange that something is actually done with the reports.

Maybe you are looking for

  • An unknown error has occurred when I try to login my apple account

    I haven't use my laptop for one month. I just found I cannot login the app store with my apple account, so i cannot purchase upgrade apps. I am using mac pro. And I just change my account password, and can login the iCloud. Help me, thank you

  • Cannot copy iTunes folder from Windows to Mac because of Permission

    I have my iTunes library on a windows machine, running windows 7. The library is organized inside the iTunes folder. I am trying to put this same iTunes onto my new macbook pro. I tried copying the folder to an external HD and plugging that into my m

  • Outlook 2010: show subfolders in Favorites for a folder in Public Folders

    I have a folder in Public Folders / All Public folders that I would like to see in my mail items favorites.  I right clicked on it, clicked "Add to Favorites" and selected the options to show subfolders (i.e. "Add subfolders of this folder").  It the

  • De-activation after I've uninstalled the program...

    I'm trying to load the entire e-Learning suite (including flash) - crashes every time!!! The machine I'm loading it on previously had Dreamweaver and Flash CS4 - I deinstalled but didn't deactivate the software. Not sure if this is the cause, but I'v

  • RFC-enabled authorization checks for specific tables?

    I am developing an Excel application which calls several BAPIs and RFC-enabled FMs, most notably RFC_READ_TABLE.  While I will provide security at the FM level by checking S_RFC for these FMs, I need to find a way of restricting access for users to s