ToString() overrides in constructor-less classes? [CS3,JS]

How do I override the toString() method in a class that lacks its own constructor?
(I'm actually working with the ManagedArticle class from Woodwing's SmartConnection plugin, but the probem appears to be general for any such class, so here we are with Page).
Example:
Page.prototype.toString = function() {
     return "[object Page "+this.name+"]";
p0 = app.activeDocument.pages[0];
$.writeln("1: "+p0);
$.writeln("2: "+p0.toString());
$.writeln("3: "+Page.prototype.toString.call(p0));
p1 = app.activeDocument.pages.add();
$.writeln("4: "+p1);
$.writeln("5: "+p1.toString());
$.writeln("6: "+Page.prototype.toString.call(p1));
produces:
1: [object Page]
2: [object Page]
3: [object Page 1]
4: [object Page]
5: [object Page]
6: [object Page 2]
Is this a fool's errand? I'd really like easier debugging of this class and overriding the toString() would seem to be the way-to-go.
Thanks!

You actually can do it to InDesign DOM objects (well some of them -- in certain ways anyhow). Here's a particularly interesting one:
var itemByLabel = function (label){
    var labelIndex = null;
    var labelArray = this.everyItem().label;
    for(var i=0;i<labelArray.length;i++){
        if(labelArray[i]==label){labelIndex = i;break}
    if(labelIndex===null){return null}
    return this.item(labelIndex);
app.documents[0].pageItems;//needed to initialize the PageItems object
PageItems.prototype.itemByLabel = itemByLabel;
app.documents[0].paragraphStyles;//needed to initialize the ParagraphStyles object
ParagraphStyles.prototype.itemByLabel = itemByLabel;
etc...
I am very wary of prototyping anything but the simplest JS objects though...
You can do it with a regular function or method in a custom library (like Bob likes to do).
function CustomToString(object){
     var string = object.toString();
     string+="bla bla bla";
     return string;
Harbs

Similar Messages

  • Constructor and Class constructor

    Hi all
    Can any one explain me the functionality about Constructor and class constructor??
    As well as normal methods, which you call using CALL METHOD, there are two special methods
    called CONSTRUCTOR and CLASS_CONSTRUCTOR, which are automatically called when you
    create an object (CONSTRUCTOR) or when you first access the components of a class
    (CLASS_CONSTRUCTOR)
    I have read the above mentioned document from SAP Documents but i found it bit difficult to understand can any one please help me on this??
    Thanks and Regards,
    Arun Joseph

    Hi,
    Constructor
    Implicitly, each class has an instance constructor method with the reserved name constructor and a static constructor method with the reserved name class_constructor.
    The instance constructor is executed each time you create an object (instance) with the CREATE OBJECT statement, while the class constructor is executed exactly once before you first access a class.
    The constructors are always present. However, to implement a constructor you must declare it explicitly with the METHODS or CLASS-METHODS statements. An instance constructor can have IMPORTING parameters and exceptions. You must pass all non-optional parameters when creating an object. Static constructors have no parameters.
    Class Constructor
    The static constructor is always called CLASS_CONSTRUCTER, and is called autmatically before the clas is first accessed, that is before any of the following actions are executed:
    Creating an instance using CREATE_OBJECT
    Adressing a static attribute using ->
    Calling a ststic attribute using CALL METHOD
    Registering a static event handler
    Registering an evetm handler method for a static event
    The static constructor cannot be called explicitly.
    For better understanding check the following code:
    REPORT  z_constructor.
          CLASS cl1 DEFINITION
    CLASS cl1 DEFINITION.
      PUBLIC SECTION.
        METHODS:
          add,
          constructor IMPORTING v1 TYPE i
                                v2 TYPE i,
          display.
        CLASS-METHODS:
         class_constructor.
      PRIVATE SECTION.
        DATA:
        w_var1   TYPE i,
        w_var2   TYPE i,
        w_var3   TYPE i,
        w_result TYPE i.
    ENDCLASS.                    "cl1 DEFINITION
          CLASS cl1 IMPLEMENTATION
    CLASS cl1 IMPLEMENTATION.
      METHOD constructor.
        w_var1 = v1.
        w_var2 = v2.
      ENDMETHOD.                    "constructor
      METHOD class_constructor.
        WRITE:
        / 'Tihs is a class or static constructor.'.
      ENDMETHOD.                    "class_constructor
      METHOD add.
        w_result = w_var1 + w_var2.
      ENDMETHOD.                    "add
      METHOD display.
        WRITE:
        /'The result is =  ',w_result.
      ENDMETHOD.                    "display
    endclass.
    " Main program----
    data:
      ref1 type ref to cl1.
    parameters:
      w_var1 type i,
      w_var2 type i.
      start-of-selection.
      create object ref1 exporting v1 = w_var1
                                  v2 = w_var2.
       ref1->add( ).
       ref1->d isplay( ).
    Regards,
    Anirban Bhattacharjee

  • Error getting Constructor[] from class.getConstructors()

    Hi,
    I am trying to use java.lang.reflect package as under:
    import java.lang.reflect.*;
    import java.lang.reflect.Constructor;
    public class reflects1
    public reflects1(String str) {
         System.out.println("string constructor");
    public static void main(String args[])
    String name = args[0];
    System.out.println("classname is:" + name);
    try {
    Class cls = Class.forName("reflects1");
         Class[] param1 = {String.class};
    Constructor const = cls.getConstructor(param1);
         } catch (Exception ex) {}
    I always get following two compilation errors:
    1) Invalid Expression Statement: Constructor[] const = cls.getConstructor(param1);
    2) ; expected, Constructor[] const = cls.getConstructor(param1);
    Please let me know if you see any problem with this statement.
    Thanks.

    You seem to be mixing getConstructor and getConstructors, which are two separate methods, only the latter returns an array.

  • Implementing constructor outside class implementation..

    REPORT  ZTUSH.
    CLASS counter DEFINITION.
      PUBLIC SECTION.
        METHODS CONSTRUCTOR.
        CLASS-METHODS: set IMPORTING value(set_value) TYPE i,
                 increment,
                 get EXPORTING value(get_value) TYPE i.
       PRIVATE SECTION.
       CLASS-DATA count TYPE i.
    ENDCLASS.
    METHOD CONSTRUCTOR.
    WRITE:/ 'I AM CONSTRUCTOR DUDE'.
    ENDMETHOD.
    CLASS counter IMPLEMENTATION.
    METHOD set.
        count = set_value.
      ENDMETHOD.
    ENDCLASS.
    DATA cnt TYPE REF TO counter.
    START-OF-SELECTION.
      CREATE OBJECT cnt.
      CALL METHOD counter=>set EXPORTING set_value = number.
    I THOUGHT WE CAN DEFINE CONSTRUCTOR METHOD OUTSIDE CLASS IMPLEMENTATION AS IN JAVA. But when I do that I get an error, method can be implemented only withing class. Why?

    Hello Rajesh
    I do not fully understand what you mean by "I THOUGHT WE CAN DEFINE CONSTRUCTOR METHOD OUTSIDE CLASS IMPLEMENTATION AS IN JAVA". However, if you mean that we can create an object without having an explicit CONSTRUCTOR method defined then this is possible in ABAP like in Java (see coding below).
    Regards
      Uwe
    REPORT ztush.
    *       CLASS counter DEFINITION
    CLASS counter DEFINITION.
      PUBLIC SECTION.
    *METHODS CONSTRUCTOR.
        CLASS-METHODS: set IMPORTING value(set_value) TYPE i,
        increment,
        get EXPORTING value(get_value) TYPE i.
      PRIVATE SECTION.
        CLASS-DATA count TYPE i.
    * NO explicit constructor
    *METHOD CONSTRUCTOR.
    *WRITE:/ 'I AM CONSTRUCTOR DUDE'.
    *ENDMETHOD.
    ENDCLASS.                    "counter DEFINITION
    *       CLASS counter IMPLEMENTATION
    CLASS counter IMPLEMENTATION.
      METHOD set.
        count = set_value.
      ENDMETHOD.                    "set
      METHOD get.
      ENDMETHOD.                    "get
      METHOD increment.
      ENDMETHOD.                    "increment
    ENDCLASS.                    "counter IMPLEMENTATION
    DATA cnt TYPE REF TO counter.
    START-OF-SELECTION.
    * Implicit constructor is called
      CREATE OBJECT cnt.
      CALL METHOD counter=>set
        EXPORTING
          set_value = 5.
    END-OF-SELECTION.

  • Overriding default constructor in extended class

    I've got some code that extends UnicastRemoteObject. The UnicastRemoteObject's default constructor open a random tcp/ip port. I'd like to control what port is opened. The UnicastRemoteObject has another constructor which takes a port as input. I'd like to override the default constructor. I've read that if I specify a call to super(<int>) that the default constructor wouldn't be called but the constructor taking an int would be called. I tried this but got both the default constructor (random tcp/ip port opened) and the constructor I called (shown by the port I specified being opened). Am I doing something wrong? Is there another way to control the constructor initiated in the class that is extended ?

    I'd like to
    override the default constructor.Yes but why?
    I've read that if I
    specify a call to super(<int>) that the default
    constructor wouldn't be called but the constructor
    taking an int would be called.Correct.
    I tried this but got
    both the default constructor (random tcp/ip port
    opened) and the constructor I called (shown by the
    port I specified being opened).I doubt this very much. You need to review your evidence for this assertion. You should call super(port) if you have a specific port in mind, and in JDK 1.5 you should call it anyway with 0 if you don't want to have to generate stubs.
    This question would be better off in the RMI forum.
    EJP

  • Problem Using toString method from a different class

    Hi,
    I can not get the toString method to work from another class.
    // First Class Separate file MyClass1.java
    public class MyClass1 {
         private long num1;
         private double num2;
       public MyClass1 (long num1, double num2) throws OneException, AnotherException {
            // Some Code Here...
        // Override the toString() method
       public String toString() {
            return "Number 1: " + num1+ " Number 2:" + num2 + ".";
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        public static void main(String[] args) {
            try {
               MyClass1 myobject = new MyClass1(3456789, 150000);
               System.out.println(myobject);
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
    }My problem is with the System.out.println(myobject);
    If I leave it this way it displays. Number 1: 0 Number 2: 0
    If I change the toSting method to accept the parameters like so..
    public String toString(long num1, double num2) {
          return "Number 1: " + num1 + " Number 2:" + num2 + ".";
       }Then the program will print out the name of the class with some garbage after it MyClass1@fabe9. What am I doing wrong?
    The desired output is:
    "Number 1: 3456789 Number 2: 150000."
    Thanks a lot in advance for any advice.

    Well here is the entire code. All that MyClass1 did was check the numbers and then throw an error if one was too high or too low.
    // First Class Separate file MyClass1.java public class MyClass1 {
         private long num1;
         private double num2;
         public MyClass1 (long num1, double num2) throws OneException, AnotherException {              
         // Check num2 to see if it is greater than 200,000
         if (num2 < 10000) {
                throw new OneException("ERROR!:  " +num2 + " is too low!");
         // Check num2 to see if it is greater than 200,000
         if (num2 > 200000) {
                throw new AnotherException ("ERROR!:  " +num2 + " is too high!");
         // Override the toString() method
         public String toString() {
              return "Number 1: " + num1+ " Number 2:" + num2 + ".";    
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        // Main method where the program begins.
        public static void main(String[] args) {
            // Instantiate first MyClass object.
            try {
               MyClass1 myobject = new MyClass1 (3456789, 150000);
               // if successful use MyClass1 toString() method.
               System.out.println(myobject);
                         // Catch the exceptions within the main method and print appropriate
                         // error messages.
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
             }I am not sure what is buggy. Everything else is working fine.

  • ToString meathod help in a class and arrys

    I can't get the toString method to work, i have a temp class and a temp client and I'm trying to call the toString method from the class in the client but its not working. Can anyone please help me out with this. THANKS!
    Here's the Temp Client:
    import java.util.Scanner;
    public class TempClient
        public static void main(String [] args)
                 Scanner scan = new Scanner(System.in);
                 int [] dailyTemps = new int [7];
                 int [] inputTemps = { 32, 45, 52, 66, 76, 53, 31};
                   Temp t1 = new Temp (inputTemps);
                   Temp t2 = new Temp (dailyTemps);
                   for ( int i = 0; i < dailyTemps.length; i ++)
                        System.out.print(" Enter the temperature for day  " + (i + 1) + "\t");
                        dailyTemps[i] = scan.nextInt ();
                                   System.out.println( t1.toString() );
                        hers the Temp class:
    import java.util.Scanner;
       public class Temp
              public final int TEMPS = 7;
              int temp;
              //String dailyTemps;     
              int [] dailyTemps;
                int [] inputTemps;
              int Temp;
              String temp1;
             //constructor
          public  Temp()
              public Temp( int [] dailyTemps)
              public  Temp(int newTemp)
                   temp = newTemp;
            public int getTemp()
                   return temp;
              public void setTemp( int changeTemp )
                   temp = changeTemp;
              public String toString(int [] inputTemps)
              String returnValue = " ";
              for(int i = 0; i < inputTemps.length; i++)
                   returnValue = returnValue + inputTemps + "\t";
                   returnValue += "\n";
                        return returnValue;

    TripleA wrote:
    man if i knew how to fix this i would not ask for help. so if you could please help me out? if not just tell me so i can go find help else where. He was being humorous (a bit). Your telling us "now it's not printing anything" gives us about as much useful information as BDLH describing his afternoon snack. You're welcome to go someplace else but they'll not be able to help you either. If it were me, I'd display my current code, and give more explanation on what's going on, but your mileage may vary.

  • Overriding default constructor in extended UnicastRemoteObject

    I've got some code that extends UnicastRemoteObject. The UnicastRemoteObject's default constructor open a random tcp/ip port. I'd like to control what port is opened. The UnicastRemoteObject has another constructor which takes a port as input. I'd like to override the default constructor. I've read that if I specify a call to super(<int>) that the default constructor wouldn't be called but the constructor taking an int would be called. I tried this but got both the default constructor (random tcp/ip port opened) and the constructor I called (shown by the port I specified being opened). Am I doing something wrong? Is there another way to control the constructor initiated in the class that is extended ?

    Betsy
    (a) You are getting the correct port, so your super(port) must be calling UnicastRemoteObject.UnicastRemoteObject(port). Yes? This is what the Java Language Spec says it should do and if it did anything else oceans of JDK code would break. The only inference possible is that this is not happening.
    (b) You're also getting another listening port. I think this is the RMI DGC server being initiated by the export of this object. (Does your object have a socket factory?) Export a few more objects and see if you get 2N listening ports or N+1.
    I'm also confused by you saying that all this happens at the client when the remote server is down. Is this a callback object?
    Can you show us the constructor of your remote object?

  • BUG: ojc compiler doesnt handle @Override on anonymous inner class methods

    Hi,
    jdev 10.1.3.3.0.4157, XP SP2, jdk 5 u13:
    for the following code sample:
    Object o = new Object()
        @Override
        public String toString2()
            return "some string";
    };With ojc set as a compiler (the default), ojc doesnt catch the error about overriding toString with toString2, changing the compiler to javac achieves the required and correct behavior.

    Thanks Frank, I logged a couple more not so serious issues a while back but didnt get any feedback on them. The subject of the posts didn't have a 'BUG' prefix though. Should I edit them so to give them some attention, or were they silently logged :) ?

  • How to override attributes of one class into another class in OOPS ABAP

    I was trying to override attribute(data memeber) defined in super class into subclass ,
    but I didnt find any solution to that.
    Please tell me ho to do that?
    Ex
    Class ABC definition
          Public section
             data : x type i.
       end class
    Calss XYZ definition inheriting from ABC.
        Publec section.
           data : x type  i.                                            <<----
    here is the problem
    endclass.

    when you define a subclass all the properties of superclass are inherited into class.
    You dont need to define it again.
    data : x type i " delete this line.
    Object of your subclass will be able to recognize x.
    Regards,
    Lalit Mohan Gupta.

  • Constructor of class A instantiating class B and vice versa

    Hi folks,
    I have two classes, namely ZCL_EMPLOYEE and ZCL_USER.
    ZCL_EMPLOYEE has an attribute USER type ref to ZCL_USER, populated by a "create object" statement in the constructor method.
    ZCL_USER has an attribute EMPLOYEE type ref to ZCL_EMPLOYEE, also populated by a "create object" statement in the constructor method.
    Thus when I instantiate one of the classes, this inevitably results in an endless loop.
    Is there any way to avoid this? I guess it must be possible to catch already instanciated objects and re-use them rather than instantiating all the time, but how?
    Thanks a lot for your help,
    Patrick

    Hello Patrick
    Since you need to create a couple of instance at the same time this is a task I would solve with the FACTORY pattern, e.g.:
    Both class contain static factory methods and the instantiation is set private as suggested by Matthew, e.g.:
    DATA:
      lo_user     TYPE REF TO zcl_user,
      lo_empl    TYPE REF TO zcl_employee.
      lo_user = zcl_user=>create( id_uname = <username> ).
      lo_empl = zcl_employee=>create( id_pernr = <personnel number> ).
    CREATE method of ZCL_USER:
    METHOD create. 
      CREATE OBJECT ro_instance    " of TYPE REF zcl_user
        EXPORTING
          id_uname = id_uname
    *      io_employee =                     " optional parameter for employee instance      
    ENDMETHOD.
    CREATE method of ZCL_EMPLOYEE:
    METHOD create.
      CREATE OBJECT ro_instance    " of TYPE REF zcl_employee
        EXPORTING
          id_pernr = id_pernr
    *      io_user  =                            " optional parameter for user instance
    ENDMETHOD.
    CONSTRUCTOR method of ZCL_USER:
    METHOD constructor.
      IF ( io_employee IS BOUND ).
        me->mo_employee = io_employee.
      ELSE.
        " get PERNR via infotype 0105
        CREATE OBJECT me->mo_employee
          EXPORTING
            id_pernr = <personnel number>
            io_user  = me.
      ENDIF.
    ENDMETHOD.
    CONSTRUCTOR method of ZCL_EMPLOYEE:
    METHOD constructor.
      IF ( io_user IS BOUND ).
        me->mo_user = io_user.
      ELSE.
        " get uname via infotype 0105
        CREATE OBJECT me->mo_user
          EXPORTING
            id_uname = <username>
            io_employee  = me.
      ENDIF.
    ENDMETHOD.
    Final remark: If you are not yet aware of class CL_PT_EMPLOYEE you may want to have a look at my Wiki posting
    [Unified Access to All HR Infotypes|https://wiki.sdn.sap.com/wiki/display/Snippets/UnifiedAccesstoAllHR+Infotypes]
    Regards
      Uwe

  • Overriding = in my AnyType class

    I am trying to create an AnyType class. I am wondering if it is possible to override the = operator like you can in C++. The AnyType class will be used in a method (setValue(AnyType type, String path)) to accept any type that is passed to it. Based on what is passed in the setValue method will be doing different things. It seems easier to handle it with a single method that will accept any type as opposed to overloading the setValue method multiple times. I am also working on using the AnyType as a return from some methods. Any suggestions? Is this possible??
    Thanks,
    Jim Pagnotta

    Hi JIM,
    As in C++ no operator overloading is possible in Java. So you cannt overload = operator . and as far as i know in c++ also you cant overide = opertor .i think you are talking about overridding == operator.
    My suggestion to this, is accept an instance of Object class as one of the parameters of your setValue() method and use instance of operator to find out the class of it and work accordingly.

  • Overriding default constructor

    I'm on Oracle 10gR2. I need to know how to override the default constructor for a user defined object. The docs say that this is possible. But it wont allow me to add a constructor with the same params as the default constructor. Does anyone know how?
    CREATE OR REPLACE TYPE period AS OBJECT (
    start_time DATE,
    end_time DATE,
    -- This fails
    CONSTRUCTOR FUNCTION period(p_start DATE, p_end DATE)
    RETURN SELF AS RESULT
    ...

    Betsy
    (a) You are getting the correct port, so your super(port) must be calling UnicastRemoteObject.UnicastRemoteObject(port). Yes? This is what the Java Language Spec says it should do and if it did anything else oceans of JDK code would break. The only inference possible is that this is not happening.
    (b) You're also getting another listening port. I think this is the RMI DGC server being initiated by the export of this object. (Does your object have a socket factory?) Export a few more objects and see if you get 2N listening ports or N+1.
    I'm also confused by you saying that all this happens at the client when the remote server is down. Is this a callback object?
    Can you show us the constructor of your remote object?

  • Overriding or nulling accessibility class metatag (JAWS)

    I am trying to disable the AccessibilityImplementation in parent components and allow children components, for example (disable a datagrid's accessibility implementation and allow the labels and text input (from that same datagrid control item renderers),  to expose their accessiblity name to jaws).
    I was able to do it, and it works perfectly using the monkey patch approach, I copied the source code from mx.controls.Datagrid.as and removed the line 534 [AccessibilityClass(implementation="mx.accessibility.DataGridAccImpl")] and it works as we need. We can also do our own AccessibilityImplementation as we need.
    The question is..  can we from an extended class, set to null the accessibilityclass meta tag value
    the following code throws a compile error, please check
    package mx.controls
    [AccessibilityClass(implementation=null)]
    public class ExDataGrid extends DataGrid
      public function ExDataGrid()
    thanks in advance

    RK-JAVA wrote:
    In one of the threads
    [http://forums.sun.com/thread.jspa?forumID=31&threadID=5328422|http://forums.sun.com/thread.jspa?forumID=31&threadID=5328422]
    I think reply 7 of 7 puts some good points.
    it says,
    The question then becomes of course why cannot variables be overridden?
    Well, technically I suppose they could be but the purpose of overriding is to change the behaviour of subclasses
    and variables don't represent behavior, they represent stateand it seems variables have nothing got to do with overriding, it is just the latest attribute up the stack that is used.Well, I was uj_ once so I wrote that. -:)
    It's just another way to express my reply #2 in this thread.
    There's a division of labour between methods and variables. Non-private methods represent the behavior of a type, whereas variables represent implementation and object state none of which should be exposed in a type. And because the purpose of the overriding mechanism is to modify the behaviour of subtypes, overriding really doesn't make sense for variables.
    There's a greyzone here though and that concerns so called "properties". Are they behavior or are they state? Well, it's bad encapsulation to expose naked variables in a type so if a variable represents a "property" it should be embedded in a getter/setter pair. This means that "properties" should be represented by methods in the type. The question now is whether a subtype should be able to override and modify a "property" defined by the superttype? Well as a programmer you can prevent that by declaring the "property's" getter/setter methods final.
    The conclusion I'm making is that naked variables never belong in a type so making them overridable makes no sense. If a variable represents a "property" it should be exposed via a getter/setter pair. The programmer then can decide whether this "property" should be overridable by declaring the getter/setter pair final or not.

  • Override shift-scrollwheel behavior in CS3/CS4?

    Does anyone know offhand if it is possible to override the shift-scrollwheel behavior via plugin creation or scripting in CS3/CS4?
    The CS3/CS4 "scroll real fast" behavior breaks Macintosh user interface conventions hugely (in the rest of the operating system shift-scrollwheel is attached to scroll horizontally).
    Thanks in advance,
    Eric.

    Would also like to know this. Scrolling is already too fast with a magic mouse, if I happen to be holding shift when I touch the mouse I will find myself suddenly at one end of the document wondering what went wrong.

Maybe you are looking for

  • Mac mini and lcd tv displays

    I currently have a g3 ibook and a g4 imac. I've been debating on what i should buy as an upgrade. I've been torn between virtually all macs including the powerbook, ibooks, imac, and the mac mini. I'm moving in a couple of months to a temporary resid

  • How to find out the latest changes in Planning Book

    HI Experts, Please let me know, is there any way to find out who has changed the values in Planning Book and when ??

  • Some Hyperlinks not Working in WebHelp

    I have several hyperlinks to .gif image files. I hyperlink to the .gif file and then choose to open in an auto sizing popup. Some of the links work, and others don't. I've checked to make sure that the properties for the ones that don't work are the

  • How to Print Margin of subsequent template (Report Builder 6.05.32.0)

    My report consists of 3 parts, part A, B and C. Each part is of different style. Therefore I use 3 templates, each for each style. Part A appears first, then B and C. Part A (based on template A): - Top margin is printed Part B (based on template B):

  • Report Painter problem with empty selection variant

    Hello, I use the cost center selection variant for the column definition in Report Painter as characteristic value. This selection variant get only the cost centers which are valid from 1.1.2003 to 31.12.2004. The column of the report created by Repo