Casting object, acessing super method

I got an example:
String o = "Java Forum";
System.out.println(o); // "Java Forum"
Object ox = (Object) o;
System.out.println(ox); // "Java Forum"
How can i access the toString() method from Object class?!
any chance?
tkz.

public class exampletoString
public static void main(String [] args)
String o = "Java Forum";
System.out.println(o); // "Java Forum"
Object ox = (Object) o;
System.out.println(ox); // "Java Forum"
//for accessing toString method of Object class override toString() method.
exampletoString etS=new exampletoString();
System.out.println(etS);//this object belongs to exampletoString
public String toString()//Override to String method
return "this object belongs to exampletoString";
}

Similar Messages

  • Calling A Super Method Externally

    Hi,
    I would like to call an overridden method, a super method, of an object externally. I thought all I needed to do was:
    1. get the java.lang.Class object of the super class where the original method was declared and implemented.
    2. get the appropriate java.lang.reflect.Method object from the Class object.
    3. override the java language protections on the Method object.
    4. Call Method.invoke() with the instance of the subclass which I wanted to call the method on.
    Unfortunately, when I got to step 4, I saw this in the documentation for Method.invoke:
    "If the underlying method is an instance method, it is invoked using dynamic method lookup as documented in The Java Language Specification, Second Edition, section 15.12.4.4; in particular, overriding based on the runtime type of the target object will occur."
    Is there any way to externally access the functionality of a super method implementation on a subclass that overrides it? It seems like there should be...
    In case you are wondering, the reason I am doing this is I am trying to implement a deep clone method. However, I would like any class to be able to call the deep clone method by passing themselves as an argument to a static method -- that way you don't have to worry about subclasses inheritting clone or anything like that. The code would look something like this (however it seems that according to the docs, this would result in an infinite recursion because when the Object.clone() method is invoked, it would actually resolve to the MyDeepCloneableObject.clone() method (which would call the utility function, which would invoke the Object.clone() again etc. etc.)):
    public class MyDeepCloneableObject implements Cloneable {
    public Object clone() {
    return ObjectUtil.deepClone(this);
    public class ObjectUtil {
    private static final Method OBJECT_CLONE_METHOD;
    private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
    private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
    static {
    //Set the OBJECT_CLONE_METHOD
    try {
    OBJECT_CLONE_METHOD =
    Object.class.getDeclaredMethod("clone", EMPTY_CLASS_ARRAY);
    OBJECT_CLONE_METHOD.setAccessible(true);
    } catch (NoSuchMethodException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    } catch (RuntimeException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    public static Object deepClone(Cloneable object, int levels) {
    Object clone;
    try {
    clone = OBJECT_CLONE_METHOD.invoke(object, EMPTY_OBJECT_ARRAY);
    } catch (IllegalAccessException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    return null;
    } catch (InvocationTargetException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    return null;
    } catch (RuntimeException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    return null;
    // Use more reflection on fields of clone to implement deep clone
    }

    In your example the clone method is not creating a clone, just returning a new instance of an object of the same type. In both cases the default shallow clone method should be implemented as follows:
    public Object clone() {
    //Call Object.clone()
    return super.clone;
    By doing so, any subclasses will also have their fields copied when clone() is called.
    From the javadocs for Object.clone():
    "The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation."
    Now as to how the parent is supposed to know about fields in subclasses, the implementation of clone is implemented in a native method in Object, so the JVM can pretty much know anything about the subobject as long as it has a reference to it. Further, if I wanted to make my own implementation, I could using reflection:
    public Object clone() {
    // Get the runtime class of this object, note that the runtime class
    // may be a subclass of the class in which this clone method is defined
    Class objectClass = this.getClass();
    //Get all of the fields in this class and it's super classes
    List fieldsList = new ArrayList();
    while (objectClass != null) {
    Field[] fields = objectClass.getDeclaredFields();
    for (int j =0; j < fields.length; j++) {
    fieldsList.add(fields[j]);
    objectClass = objectClass.getSuperClass();
    //Now I can create a new instance of the runtime class and set
    //all of its fields appropriately
    However, I'm sure the JVM's implementation is far more efficient.
    I have not benchmarked serialization. However, all the steps in my procedure would have to be done for serialization anyway (i.e. get list of all fields, instantiate equivalent field values and set them in the new object), but serialization also needs to convert everything to a byte representation and then parse it out again. Furthermore, serialization will perform a fully deep clone, where as I only want a one level deep clone (or two depending on how you think of it -- i.e. not a shallow copy of references (as Object.clone(0 does), but a copy of direct fields and containers (i.e. Maps and Collections in fields should be cloned, but not objects in the Maps and Collections). So if an object has a field which is a List and the List field contains 1 entry, and the object is cloned, then subsequent modifications to the List field in the cloned object are not reflected in the original object's List field and vice versa (i.e. the 1 entry is removed in the original , but remains in the clone's version of the List field).

  • Casting & abstract class & final method

    what is casting abstract class & final method  in ABAP Objects  give   some scenario where  actually  use these.

    Hi Sri,
    I'm not sure we can be any more clear.
    An Abstract class can not be instantiated. It can only be used as the superclass for it's subclasses. In other words it <b>can only be inherited</b>.
    A Final class cannot be the superclass for a subclass. In other words <b>it cannot be inherited.</b>
    I recommend the book <a href="http://www.sappress.com/product.cfm?account=&product=H1934">ABAP Objects: ABAP Programming in SAP NetWeaver</a>
    Cheers
    Graham

  • Error in calling Super() method cannot reference ...

    import javax.swing.JFrame;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class MyFrame extends JFrame {
    String St="Rayudu";
         JPanel jp1= new JPanel();
         JButton jb1=new JButton("Hello");     
    public MyFrame() {
    super("Document :" + St);
              jp1.add(jb1);
              getContentPane().add(jp1);
    //...Then set the window size or call pack...
    setSize(300,300);
    //Set the window's location.
         setLocation(300,300);
         setVisible(true);
    public static void main(String ar[])
    MyFrame mf=new MyFrame();
    mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    C:\java>javac My*.java
    MyFrame.java:11: cannot reference St before supertype constructor has been called
    super("Document :" + St);
    ^
    1 error
    Can anyone explain?
    thanks in advance.

    Change your constructor to take an argument of type String, pass this along to the super method when you call the new instance of your class in main. ie:
    public myFrame( String title ) {
    super( "Document: " + title );
    st = title; //if you need it in that String Object assign it here.
    //etc...
    public static void main( String args[] ) {
    new myFrame( "Testing" );
    Does this answer your question?

  • About casting objects.

    From what I understand, a child class inherits all the properties from its parent class and it may contains additional properties that the parent class does not have. Suppose the parent and child classes are declared as follows.
    class Parent {
    public void parentX() {}
    class Child {
    public void ChildX() {}
    If I cast a child object to a parent object by doing:
    Child c = new Child();
    Parent p = (Parent)c;
    .. and then cast it back to child class.
    Child c2 = (Child)p;
    I can still access c2.ChildX(). I was guessing that when you do a upcast (child->parent), the child-specific properties are lost because the parent variable was not allocated enough memory to hold the additional properties. But the above example proves otherwise. Can someone explain?

    And casting is mostly telling the compiler what member
    methods you have. Because three classes could all have
    a method toString() so the compiler needs to know
    which of these you mean when you put c.toString().I dont think if you have the same method for both parent and child class, casting will changes which one is called. For example, if a callme() is added as follows:
    class Parent {
    public void callme() { System.out.println("in parent"); }
    class Child extends Parent {
    public void callme() { System.out.println("in child"); }
    And if you do:
    Parent p = (Parent)(new Child);
    p.callme();
    This will print out "in child". So casting doesnt change which method is called.

  • Casting objects with reflection possible?

    I have this code:
    String className = "com.xyz.MeasurementUnit";
    Class provider = Class.forName(className + "Provider");
    Object object = context.getContractProxy(provider);The last line returns an object of type object. I must execute the method getIsoId(...) on that object. But to do that, I think I have to cast it first to the object type MeasurementUnitProvider.
    Is this possible with reflection? Is it somehow possible to solve what I want to do?

    If MeasurementUnitProvider is an interface that is known at compile time, then the cast can be made in the usual way MeasurementUnitProvider unitProvider = (MeasurementUnitProvider)context.getContractProxy(provider);If the interface is not known at compile time, then the object reflecting the method can be obtained from the Class object by name and parameter type. For reflective method invocation, no cast is required.
    Pete

  • T cast(Object obj)

    Hi,
    What is the actual use of this method T cast(Object obj) that "casts an object to the class or interface represented by this Class object." ?
    If we pass the class token as a parameter then we already know what type it is and this seems to be the only way to to determine the concrete type at runtime. How is this method used ?
    Thanks,
    Mohan

    Class.cast helps you avoid an "Unchecked" warning. That's about all there is to it. Example:
    import java.util.HashMap;
    import java.util.Map;
    public abstract class Factory<T> {
         public abstract T newInstance();
         public static <TT> TT createObject(Class<TT> clazz) {
              Factory<?> factory = factories.get(clazz);
              if(factory == null)
                   throw new IllegalArgumentException("invalid class "+clazz.getName());
              return (TT)factory.newInstance(); // Unchecked warning
         public static <TT> void registerFactory(Class<TT> clazz, Factory<? extends TT> factory) {
              factories.put(clazz, factory);
         private static final Map<Class<?>, Factory<?>> factories = new HashMap<Class<?>, Factory<?>>();
    }The line with the comment will trigger an "Unchecked" warning, which could be avoided by using
    return clazz.cast(factory.newInstance());

  • Safe Casting Collections using utility methods

    Hi,
    I am wondering, are there any utility methods that help extract the elements form one collection<?> to Collection<Box>??
    for example, I may have a method signiture that takes List<Box> as a parameter called doYourJob.
    and I have a List of List< ? extends Object> someList.
    ofcourse I cant use this object for that method:
    List<? extends Object> someList;
    doYourJob(someList);//wrong
    public void doYourJob(List<Box>list){
    }what I need to do is to make a utility method that extracts a spisific type from the collection and puts them in another collection:
    public List<Box> extract (List<?>list){
    ArrayList<Object>newList=new ArrayList<Object>();
    for(Object o:list){
    if(o instanceof Box)newList.add((Box)o);
    return newList;
    }my question is: are there in the jave API utility methods to change the generic type of a collection by changing the collection as whole.
    Maybe I can send the type that I want as Box.class and it returns that list.
    Sorry if the question is repetitive!

    I wish his was something that was easier to do in
    Java because I think more people would use that
    approach if it weren't so verbose.
    Maybe I'm confused here, but I don't think of coding
    up an interface as being an especially verbose or
    arduous exercise...? But then I'm not too sure what
    you're comparing it with.It's not writing the interface that's the problem. It's writing the code to wrap the existing classes in your wrappers or whatever implementation you come up with. Doing it once is no big deal but if you are using it as a fairly common approach in your code (as I do) it can become pretty messy. What really bothers me is that it takes a lot of fluff code. I've been looking at other languages esp. Scala on this and they have very concise composition syntax. I'm not ready to go with Scala but I think if the language steered people more towards composition and 'recasting' objects through interfaces, people would do more of it.
    I'm working with one now that's all about return
    codes and simulating in-out parameters (I said it
    once and I'll say it again: Joel Spolsky is an
    idiot.)
    Hmm. I read Joel On Software, and from a business
    perspective he seems pretty clued in. I've never
    encountered any of his code, nor read anything much
    of a purely technical-diatribe nature from him. But
    I'm still alittle surprised.Not sure if you've read this:
    http://www.joelonsoftware.com/items/2003/10/13.html
    I'm exaggerating, of course. I don't really think he's an idiot but I think the above is super-extra-double-plus stupid. I really can't fathom why he thinks return codes are superior. I can only think he doesn't really get how exceptions work.
    There's also this ironically named URL:
    http://www.joelonsoftware.com/articles/Wrong.html

  • Muse JS Assert: Error calling selector function:Type error: Object has no method Muse Menu

    When exporting html and viewing locally we receive the following error... This error disappears after removing menu from top of page. This error does not occur when viewed on Outdoors360.businesscatalyst.com (our temporary site)
    Muse JS Assert: Error calling selector function:Type error: Object has no method Muse Menu
    Any ideas??

    I fix the problem.
    I have carefully reviewed JAVASCRIPT files and I could see that these are not a major influence within the site, only are reference code and utilities of the same application.
    By removing these files nothing has stopped working, I thought I would have some error in the sliders, or opacities, but no, nothing happened.
    DELETE IT
    FRANCISCO CATALDO DISEÑADOR GRÁFICO

  • How to create new java objects in native methods?

    Hello,
    Is it possible to create java objects and return the same to the java code from a native method?
    Also is it possible to pass java objects other than String objects (for example, Vector objects) as parameters to native methods and is it possible to return such objects back to the java code?
    If so how can I access those objects (say for example, accessing Vector elements) inside the native code?
    What should I do in order to achieve them?
    Regards,
    Satish

    bschauwe is correct in that constructing Java objects and calling methods on Java objects from native code is tough and takes some study. While you're at it, you might want to check out Jace, http://jace.reyelts.com/jace. It's a free open-source toolkit that really takes the nastiness out of doing this sort of stuff. For example,/**
    * A C++ function that takes a java.util.Vector and plays around with it.
    public void useVector( java::util::Vector& vector ) {
      // Print out all the contents of the vector
      for ( Iterator it = vector.iterator(); it.hasNext(); ) {
        cout << it.next();
      // Add some new elements to the vector
      vector.addElement( "Hello" );
      vector.addElement( "world" );
    } All this code just results in calls to standard JNI functions like FindClass, NewObject, GetMethodID, NewStringUTF, CallObjectMethod, etc...
    God bless,
    -Toby Reyelts

  • Can I call an object with synchronized methods from an EJB

    I have a need for multiple threads (e.g. Message Driven Beans) to access a shared object, lets say a singleton, I'm aware of the "you can't have a singleton in the EJB world" issues) for read/write operations, so the operations will need to be synchronised.
    I've seen various statements such as you can't use read/write static fields in EJBs and you can't use synchronisation primitives in EJBs but I've also seen statements that say its okay to access utility classes such as Vector (which has synchronised methods) from an EJB.
    Does anyone know if there is a definitive answer on this? What are the implications of accessing a shared object with synchronised methods from multiple EJBs? Is it just that the EJB's thread may block which limits the ability of the container to manage the EJBs? In the Vector example above (from Professional Java Server Programming) did they mean its okay to use these utility classes provided they aren't shared across threads?
    If I can't use a plain old Java Object does anyone know if there are other potential solutions for sharing objects across EJBs?
    In my problem, I have an operation that I want to run in a multi-threaded way. Each thread will add information to the shared object, and this info may be used by the other threads. There's no lengthy blocking as such other than the fact that only one thread can be adding/reading information from the shared object at a time.
    I've trawled through this forum looking for similar questions of which there seem to be many, but there doesn't seem to be any definitive answers (sorry if there was and I missed it).
    Thanks
    Martin

    You can share objects among EJB's or among objects used by one or more EJB's. You can use synchronization primitives - nothing will prevent you from doing that.
    After all, the container classes, JVM-provides classes, JDBC, JCA, JNDI and other such classes do all of this with impunity. You can too. You can use file and socket I/O as well, presuming you configure the security profile to allow it. Should you? Well it depends on what you need to accomplish and if there is another practical alternative.
    Yes the specification warns you not to, but you cannot be responsible for the interior hidden implementation of classes provided to you by the JVM or third parties so you can never truly know if your are breaking these written rules.
    But when you do these things, you are taking over some part of the role of the container. For short running methods that only block while another thread is using the method or code block and no I/O or use of other potentially blocking operations are contained in the method/block, you will be fine. If you don't watch out and create deadlocks, you will harm the container and its managed thread pool.
    You should not define EJB methods as synchronized.
    Also, if you share objects between EJB's, you need to realize that the container is free to isolate pools of your EJB in separate classloaders or JVM's. It's behavior can be influenced by your packaging choices (use of .ear, multiple separate .jar's, etc.) and the configuration of the server esp. use of clustering. This will cause duplicate sets of shared classes - so singletons will not necessarily be singleton across the entire server/cluster, but no single EJB instance will see more than one of them. You design needs to be tolerant of that fact in order to work correctly.
    This isn't the definitive answer you asked for - I'll leave that to the language/spec lawyers out there. But in my experience I have run across a number of occasions where I had to go outside of the written rules and ave yet to be burned for it.
    Chuck

  • How to use an object's paint method

    I have created a class imagePanel which extends a jPanel to display an image. When I create a new imagePanel object I pass it an image argument which is used to paint my image on the jPanel, so far so good. I don't wish to have to continuously create new ImamePanels to display new images so I thought I could make a set_Image method that would set a new image in an exising imagePanel object. This is where I run into problems how to use the existing object paint method to replace the image. I tried this without success:
    public Image setMyImage (Image myImage)
    imageX = myImage; // imageX is the image that is painted by the imagePanel object's paint method
    paint(g);
    Something must be wrong on how I access the paint method. Thanks for any help.
    Jack

    Yahoooo, got it. This was the code I needed and thanks for your help:
    public void setImage (Image myImage)
    imageX = myImage;
    repaint(300);
    }

  • Unable to cast object of type 'Oracle.DataAccess.Types.OracleDecimal'......

    I have some Oracle Tables with sequences for primary key and stored procs in packages to wrap up the insert commands. The sequences field are all declared as NUMBER.
    I also have Datasets based on the tables and a DataAdapter for each package. The Datasets see the primary keys as System.Decimal. The DataAdapter sees the output primary key parameter to the stored procs as OracleDecimal.
    tmp.Parameters.Add(new OracleParameter("P_ID", Oracle.DataAccess.Client.OracleDbType.Decimal, ParameterDirection.Output));
    tmp.Parameters["P_ID"].SourceColumn = "ID";
    When I call the Update on the DataAdapter the update happens on the DB and then I get the following error
    System.ArgumentException : Unable to cast object of type 'Oracle.DataAccess.Types.OracleDecimal' to type 'System.IConvertible'.Couldn't store <231> in ID Column. Expected type is Decimal.
    ----> System.InvalidCastException : Unable to cast object of type 'Oracle.DataAccess.Types.OracleDecimal' to type 'System.IConvertible'.
    If I change the Oracle parameter to Oracle.DataAccess.Client.OracleDbType.Int32 or Oracle.DataAccess.Client.OracleDbType.Int64 it works fine - any ideas why that would be ? I would expect System.Decimal to map to Oracle.DataAccess.Types.OracleDecimal.

    Hi,
    If I change the Oracle parameter to Oracle.DataAccess.Client.OracleDbType.Int32 or Oracle.DataAccess.Client.OracleDbType.Int64 it works fine - any ideas why that would be ? I would expect System.Decimal to map to Oracle.DataAccess.Types.OracleDecimal.
    I'm trying to do the same, but no matter what I do, I get the OracleDecimal error. Parameter is defined as:
    bq. this._adapter.InsertCommand = new global::Oracle.DataAccess.Client.OracleCommand(); \\ this._adapter.InsertCommand.Connection = this.Connection; \\ this._adapter.InsertCommand.CommandText = "INSERT INTO PERSON\r\n                      (ID, SURNAME, NAME, BIRTHCITY, EMSO)\r\nV" + \\ +"ALUES (:ID, :SURNAME, :NAME, :BIRTHCITY, :EMSO) RETURNING ID INTO :ID";+ \\ this._adapter.InsertCommand.CommandType = global::System.Data.CommandType.Text; \\ param = new global::Oracle.DataAccess.Client.OracleParameter(); \\ param.ParameterName = "ID"; \\ param.DbType = global::System.Data.DbType.Int32; \\ param.OracleDbType = global::Oracle.DataAccess.Client.OracleDbType.Int32; \\ param.Direction = global::System.Data.ParameterDirection.Output; \\ param.IsNullable = true; \\ param.SourceColumn = "ID"; \\ this._adapter.InsertCommand.Parameters.Add(param);
    But no luck...

  • Unable to cast object of type OracleXmlType to type XmlDocument

    Hello All:
    I have an Oracle Procedure that is taking an XML Document as an output parameter.
    oCommand.Parameters.Add("errorrecord", OracleDbType.XmlType).Value = System.DBNull.Value;
    oCommand.Parameters["errorrecord"].Direction = System.Data.ParameterDirection.Output;
    When I try to cast this as an XmlDocument so I can set it to my ErrorRecord variable (defined as XmlDocument) and pass it back out of the Web-Service
    ErrorRecord = (XmlDocument)oCommand.Parameters["p_errorrecord"].Value;
    I get the following error: "Unable to cast object of type 'Oracle.DataAccess.Types.OracleXmlType' to type 'System.Xml.XmlDocument'"
    How do I cast / convert the Oracle XMLType back to a .Net XMLDocument to pass out of the function?
    Thanks

    No, I have not tried that yet, but I admit I don't fully understand the syntax in the document posted.
    oCommand.Parameters.Add("p_errorrecord", OracleDbType.XmlType).Value = System.DBNull.Value;
    ErrorRecord = GoCommand.Parameters["errorrecord"].Value; (this is returned as XmlType)
    I don't quite understand the syntax in the posted URL:
    Declaration
    // C#
    public XmlDocument GetXmlDocument();
    How am I to use this to get the XMLDocument?

  • 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

Maybe you are looking for