How to Println () my class?

Hi,
I created a new clase called: "MyClass".
Public class MyClass{
private int classid;
public getClassId();
// more code
Now I want to use the following line:
myClass myc = new myClass("test",1);
System.out.println("This is my class: " + myc);
Is there a method that I can override so I can print - let's say my class id?

My usual coding habit:
public class MyClass {
private String id;
private String name;
private int value;
public String toString() {
String debug = this.getClass().getName() +"["
+ "id='" +
+ "id='" + this.getId() + ",
='" + this.getId() + ", "
+ "name='" +
+ "name='" + this.getName() + ",
+ this.getName() + ", "
+ "value='" +
+ "value='" + this.getValue() +
+ this.getValue() + "]";
return debug;
Regards.Hi,
I tried to use your example but I got the following
error:
The method getId() is undefined for the type Class
Can you tell me why please?
Thanks.It was just a partial example (as suggested by the //... comment) ... I let you imagine what the getId() method can be.

Similar Messages

  • How do I find classes in a package

    Hi,
    I am working on an automation tool which is to be used for testing public API's in our product. The tool is supposed to work this way:
    1. A developer of the API adds a new java file containing the test code for the API in a particular package (which the tool defines). Then he compiles and places the stuff in a jar. There is also a driver class in this same package path defined by the test tool. E.g.
    driver class: com.aaa.bbb.DriverClass
    new API test file: com.aaa.bbb.TestFile
    Now the driver file's job is to find out all the other classes in this particular package and then do some processing. When I tried doing the getPackage() on this driver class to find out about the package I got back a null.
    Question 1: How can I get the package for a particular class (An ugly way to do this would be to strip it out from the classname)
    Question 2: How can I find out what other classes are there in a package?
    Thanks in advance on this.
    Nikhil Singhal
    You can also send me mails at
    [email protected]

    hai
    i have the same problem to finding the classes in package...
    in my case i know the jars name and i have loaded
    classes using code
    ResourceBundle bundle = ResourceBundle.getBundle("source\\ClasssPath");
    StringTokenizer stToke = new StringTokenizer(bundle.getString("ClassPath"),";");
    String temp;
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    while(stToke.hasMoreTokens())
         temp = stToke.nextToken().trim();
    if(temp.endsWith(".jar"))
    JarFile jar = new JarFile(new File(temp));
         Enumeration en = jar.entries();
         String pathStr;
         while(en.hasMoreElements())
         pathStr = en.nextElement().toString();
         System.out.println("pathStr ="+pathStr);
         if(pathStr.endsWith(".class"))
              System.out.println( classLoader.getResource(pathStr));
              System.out.println(classLoader.loadClass(pathStr.substring(0,pathStr.indexOf(".class")).replace('/','.').trim()));
         else classLoader.loadClass(temp);
    here i am getting the classes in that package using code
         String[] filLis = new File("//it//sella//converter//ptlf//startup//").list();
         int length = filLis.length;
         while(length-- >0)
         System.out.println(">"+filLis[length]);
    but its returnign the class when this classes in locale folder(i.e)its not getting the classes in loaded memory...
    so how to retrieve the class files names using package structure name...
    (i am having more then 20 jars files, inthat inside the jar samepackage structue may appear in more then one jars )
    pls help me in this field..
    Thanx

  • How to create a class using java script..

    Hi all,
    Iam new to java script and I tried out the following program but its not working..I basically created a class just like a java prog' but Iam not getting any output or error.Iam attaching the code below.
    If I created one function inside the script and create one object its working fine but what should I do when I have a lot of function??so I created a class and put all the function and created an object but its not working..
    Do let me know what changes should I do..Iam attaching the code which I had written. or give me an example of how to create a class with couple of functions using JAVASCRIPT
    Thanks
    Avis_su
    <html>
    <head><title>JSP Page</title></head>
    <body>
    <SCRIPT language = "JavaScript">
    <!--
    //Created classes
    class book
    var title: String;
    var author:String;
    function author()
    doucument.write("Author is " +this.author);
    function tile()
    doucument.write("Title is " +this.title);
    function printall()
    var counter = 0;
    function author();
    function title();
    var chapters = Array[String];
    for(chapter in this chapters)
    counter++;
    document.write("Chapter" counter" :"+this.chapters[chapter]+"<br>");
    var thisbook = new book()
    thisbook.author = "Sivagami";
    thisbook.title = "MS in CS giude";
    thisbook.chapters = new Array[10];
    thisbook[0] = "Prepare to Excell in all ";
    thisbook[1] = "Learn to be happy";
    thisbook[2] = "Learn to be healthy mentally emotionally physically";
    thisbook[3] = "Siva and Subbu along with kidssssss will be successful in future";
    thisbook.printall();
    //-->
    </script>
    </body>
    </html>

    Run this program to get your answer:
    public class AnswerToYourPost {
    public static void main(String args[]) {
    System.out.println("TRUE/FALSE: This question
    ion belongs on a Java forum.\n"
    + "ANSWER: " + ("Javascript" == "Java"));
    }Since when do we compare objects for equality using operator == ?

  • How do i put classes in package in NetBean Environment

    Hello,
    I install NetBean IDE for developing website using JSP and Servlet. I am using Internal Tomcat provided by this IDE.
    Problem is this i put java classes in the Class folder of Web-INF folder, but i am not able to access these classes from JSp page.
    I try to put these classes in Package but even though i use package option IDE does not put classes in the package.
    I am using internal compiler provided by this IDE for compiling java class' source file.
    What should i do, please help me
    Thank you

    hai
    i have the same problem to finding the classes in package...
    in my case i know the jars name and i have loaded
    classes using code
    ResourceBundle bundle = ResourceBundle.getBundle("source\\ClasssPath");
    StringTokenizer stToke = new StringTokenizer(bundle.getString("ClassPath"),";");
    String temp;
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    while(stToke.hasMoreTokens())
         temp = stToke.nextToken().trim();
    if(temp.endsWith(".jar"))
    JarFile jar = new JarFile(new File(temp));
         Enumeration en = jar.entries();
         String pathStr;
         while(en.hasMoreElements())
         pathStr = en.nextElement().toString();
         System.out.println("pathStr ="+pathStr);
         if(pathStr.endsWith(".class"))
              System.out.println( classLoader.getResource(pathStr));
              System.out.println(classLoader.loadClass(pathStr.substring(0,pathStr.indexOf(".class")).replace('/','.').trim()));
         else classLoader.loadClass(temp);
    here i am getting the classes in that package using code
         String[] filLis = new File("//it//sella//converter//ptlf//startup//").list();
         int length = filLis.length;
         while(length-- >0)
         System.out.println(">"+filLis[length]);
    but its returnign the class when this classes in locale folder(i.e)its not getting the classes in loaded memory...
    so how to retrieve the class files names using package structure name...
    (i am having more then 20 jars files, inthat inside the jar samepackage structue may appear in more then one jars )
    pls help me in this field..
    Thanx

  • How to use java class in pl/sql

    Hai Guys,
    here is my java class:
    import java.io.*;
    public class ListFiles
    public static void main (String[] args)
    File file=new File("C:\\");
    File[] files=file.listFiles();
    for(int fileInList=0; fileInList<files.length; fileInList++ )
         System.out.println(files[fileInList].toString() );
    i want to use this class in pl/sql, i am new about this topic my concern are following
    how to load java class
    how to use in pl/sql
    Guys i'll be great-full to you if you could help me out or share link or document .

    First Read https://forums.oracle.com/forums/ann.jspa?annID=432
    Check this link...
    1. http://www.devshed.com/c/a/Oracle/Extending-PLSQL-with-Java-Libraries-concluded/
    2. calling java from pl/sql in oracle 10g?its very urgent.
    3. http://qamarsyed.blogspot.com/2010/07/calling-java-from-plsql-inside-oracle.html
    4. http://home.c2i.net/toreingolf/oracle/java_and_plsql.htm
    Hope this helps...
    If someone response is helpful or correct, please mark it accordingly.

  • Anyone know how to find available classes in a package?

    Anyone know how to find available classes in a package?
    Given a String like "java.io" I would like to write a method to extract the available classes in this package. I can't seem to find a method for this anywhere in the docs. The package class does not seem to have a method like this.

    Here is some code I tried.
    I'm not very familiar with manipulating JARs The code below is what I tried, but how do I access the packages like "java.io" in the JarFile? and then get the available classes?
    import java.io.*;
    import java.util.*;
    import java.util.jar.*;
    class Tester
         public static void main(String args[])
              try {
                   JarFile jf = new JarFile("c:/jdk1.3/lib/dt.jar");/* usually rt.jar (and 1.4)*/
                   Enumeration e = jf.entries();
                        while (e.hasMoreElements())
                             Object current = e.nextElement();
                             System.out.println(current.toString() + "class:"+current.getClass());
                             try {
                                  Thread.sleep(300);
                             } catch (InterruptedException ie) {}
              } catch (IOException ioe) {System.out.println(ioe.toString());}
                   /*also tried      ClassLoader cl = ClassLoader.getSystemClassLoader();
              try {
                   Enumeration e = cl.getResources("c:/jdk1.3/lib/dt.jar");
                   System.out.println(e.nextElement());
                   while (e.hasMoreElements())
                   System.out.println(e.nextElement());
              } catch (IOException ioe) {System.out.println(ioe.toString());}

  • How to convert the class in the one package to same class in the other pack

    How to convert the class in the one package to same class in the other package
    example:
    BeanDTO.java
    package cho3.hello.bean;
    public class BeanDTO {
    private String name;
    private int age;
    * @return
    public int getAge() {
         return age;
    * @return
    public String getName() {
         return name;
    * @param i
    public void setAge(int i) {
         age = i;
    * @param string
    public void setName(String string) {
         name = string;
    BeanDTO.java in other package
    package ch03.hello;
    public class BeanDTO {
    private String name;
    private int age;
    * @return
    public int getAge() {
         return age;
    * @return
    public String getName() {
         return name;
    * @param i
    public void setAge(int i) {
         age = i;
    * @param string
    public void setName(String string) {
         name = string;
    My converter lass lokks like
    public class BeanUtilTest {
         public static void main(String[] args) {
              try
                   ch03.hello.BeanDTO bean=new ch03.hello.BeanDTO();
              bean.setAge(10);
              bean.setName("mahesh");
              cho3.hello.bean.BeanDTO beanDto=new cho3.hello.bean.BeanDTO();
              ClassConverter classconv=new ClassConverter();
              //classconv.
              System.out.println("hi "+beanDto.getClass().toString());
              System.out.println("hi helli "+bean.toString()+" "+bean.getAge()+" "+bean.getName()+" "+bean.getClass());
              Object b=classconv.convert(beanDto.getClass(),(Object)bean);
              System.out.println(b.toString());
              beanDto= (cho3.hello.bean.BeanDTO)b;
              System.out.println(" "+beanDto.getAge()+" "+beanDto.getName() );
              }catch(Exception e)
                   e.printStackTrace();
    But its giving class cast exception. Please help on this..

    Do you mean "two different layers" as in separate JVMs or "two different layers" as in functional areas running within the same JVM.
    In either case, if the first class is actually semantically and functionally the same as the second (and they are always intended to be the same) then import and and use the first class in place of the second. That's beyond any question of how to get the data of the first into the second if and when you need to.
    Once you make the breakthrough and use one class instead of two I'd guess that almost solves your problem. But if you want to describe your architecture a little that would help others pin down want you're trying to do.

  • How to use TableSorter class with DefaultTableModel

    Hi Friends
    Please tell me how to use TableSorter Class which is in the Java. Tutorials with DefaultTableModel.
    i saw in a thread there it was given that we have to pass the DefaultTableModel to the TableSorter Class.
    I tried to use like that. But i am getting Error Like Exception occurred during event dispatching:
    I am posting the part of Code where i use the DefaultTableModel
         private void displayavailablity(String selectedAuthor)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        String bname,bauthor,bcategory,bref1,bavail,bid;
                        int bref,mid,num;
                        rs = st.executeQuery("SELECT BId,BName,BAuthorName,BAuthorandPublisher,BCat FROM Books where BAuthorandPublisher='" +selectedAuthor+"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"NUMBER","BOOK NAME","AUTHOR","CODE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        TableSorter sorter = new TableSorter((DefaultTableModel)table.getModel());
                        rs.close();
                   catch(SQLException ex)
                        System.out.println("ERROR IS HERE");
                        ex.printStackTrace();
         }Please help me on this issue Otherwise Please give me some Sample coding to implement this sorting. with DefaultTableModel
    Thank you for your service
    Cheers
    Jofin

    I don't know about any TableSorter class, but I suppose you mean javax.swing.table.TableRowSorter.
    The TableRowSorter is to be attached to the JTable, not to the data model. Here's a cut'n'paste from the last time I used it:
    RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel);
    myTable.setRowSorter(sorter);
    And heres from the JDK1.6 documentation:
    TableModel myModel = createMyTableModel();
    JTable table = new JTable(myModel);
    table.setRowSorter(new TableRowSorter(myModel));
    Check out http://java.sun.com/javase/6/docs/api/javax/swing/table/TableRowSorter.html. I find it to be good documentation.

  • How to typecast Object Class object dynamically

    Hai every one
    i have a object of any particular class , but i don't know the variables in that class object. But i have string variable contains value of variables in that class object.
    So i use following method for get value of variables in that class object.
    class ObjectCLass
         Sub s=new Sub();
         public static void main(String[] args)
              ObjectCLass a=new ObjectCLass();
              try
                   System.out.println(*a.getClass().getDeclaredField("s").get(a)*);
              catch(Exception e)
                   System.out.println("Exception");
    class Sub
         int i=5;
         public void print()
              System.out.println("Hello World!");
    }Here the bolder line give Object class object. By using this Object class object i need access the variable i and method print(). So i need to cast Object class object into sub class
    so how can i typecast it
    i try with following methods , but i cant succeed
    1.(  *(a.getClass().getDeclaredField("s").get(a).getClass)*   a.getClass().getDeclaredField("s").get(a)   ).print() ;
    2.(  (Class.forName(�Sub�) ) a.getClass().getDeclaredField("s").get(a) ).print();Please any one one help me how to typecast it dynamically
    By
    Thiagu

    If you know you're going to invoke the "print" method on an object, then you also need to know the type of the class, or interface, which has that method.
    It seems what you are looking for is a tutorial on interfaces.
    http://java.sun.com/docs/books/tutorial/java/IandI/index.html
    In a nutshell, you can set up an interface which defines a "print" method, and create class(es) which implement that interface. Then as long as you have an object which implements that interface, but do not know the exact type of that object, you can simply cast it to the interface type and invoke the method.

  • How to Execute different classes using editplus

    Consider a program like this
    class abc
    public static void main(String args[])
    System.out.println("abc");
    class bbc
    public static void main(String args[])
    System.out.println("bbc");
    In this program there are two classes when i compile this code in editplus i wont get any error but if i want to execute only ABC class how to do that in editplus because in editplus we usually set the file name for JAVA execution
    But here it is different SO,how to execute different classes in a program which is saved with arbitary name in EDIT PLUS..

    Try reading an editplus FAQ or posting to an editplus forum or even searching through help in editplus.

  • How can update my class instance at runtime?

    What would happen if at runtime I update a class file?
    Will the JVM know to use that instead?
    How can I use the updated class at runtime?
    Who can give me an example?
    thanks all!

    yes,I write it like these:
    //MyClassLoader.java
    import java.io.*;
    public class MyClassLoader extends ClassLoader
         public Class loadClass(String name,boolean resolve)
              throws ClassNotFoundException{
              //return super.loadClass(name,resolve);
              Class c=findClass(name);
              resolveClass(c);
              return c;
         public Class loadClass(String name)
              throws ClassNotFoundException{
              return loadClass(name,true);
    public Class findClass(String name) {
    byte[] b = loadClassData(name+".class");
    //return defineClass(name, b, 0, b.length);
              Class c=null;
              System.out.println("load--class--data--success!");
              c=defineClass(name,b,0,b.length);
              System.out.println("define class success!");
              return c;
    private byte[] loadClassData(String name) {
    // load the class data from the connection
         byte[] b=null;
         try{
              //DataInputStream in =
    //new DataInputStream(
              BufferedInputStream in=
    new BufferedInputStream(
    new FileInputStream(name));
              int len=in.available();
              b=new byte[len];
              in.read(b,0,len);
              System.out.println("load "+name+" is success!\n"+name+"'s length is"+len);
         }catch(Exception e){System.out.println("load--"+name+"--data error:"+e);}
         return b;
    //Client.java
    import java.io.*;
    public class Client
         public static void main(String[] args)
         try{
              System.out.println("����������Load��������������");
              DataInputStream input=new DataInputStream(System.in);//��������������Load��������������
              MyClassLoader loader=new MyClassLoader();
              Load load=(Load)loader.loadClass(input.readLine()).newInstance();
              while(true){
                   load.print(); //print a sentence here! I will modify it when Client is runing!
                   input=new DataInputStream(System.in);
                   String inStr=input.readLine();
                   if(inStr!=null && inStr.trim()!=null)
                        load = (Load)loader.loadClass(inStr).newInstance();
         }catch(Exception e){System.out.println("main error:"+e);}
    I skip the Load interface and it's sub class,it's easy.
    MyClassLoader can load my class from the disk!
    why?

  • Urgent! how to create such class?

    A a0 = new A();
    A a1 = new A(1);
    A a2 = new A(2);
    A a3 = new A();
    a3.setNumber(3);
    System.out.println( a0 + ", " + a1 + ", " + a2 + ", " + a3 );
    I want to get output like this: 0, 1, 2, 3
    So how should I create class A? what I get confused is I must get integer number directly by referring to a0, a1...instead of a0.val, a1.val..., I try to extend Integer class as following but it does not work. Any help is appreciated.
    public class A extends Integer
    public A()
    super(0);
    public A(int num)
    super(num);
    public void setNumber(int num)
    super.SetNumber(num);

    I did this while i was sleepy! It should be:
    public class A{
         Integer integer;
         A(){
              this(0);
         A(int a){
              setNumber(a);
         public String toString(){
              return integer.toString();
         public void setNumber(int a){
              integer = new Integer(a);
         public static void main(String args[]){
              A a0 = new A();
              A a1 = new A(1);
              A a2 = new A(2);
              A a3 = new A();
              A a4 = new A();
              a3.setNumber(3);
              System.out.println( a0 + ", " + a1 + ", " + a2 + ", " + a3 );
    }     The variable a is not needed and the constructor can call the method
    setNumber.This version is better.

  • How to access super class's super class

    Hello every one.
    I have a question.
    if I have a class like:
    public class A {
    void methoda() {
    void methodb() {
    and a class B extends A and override A's methoda
    public class B extends A {
    void methoda() {
    and a class C extends B which want use A's methoda.
    public class C extends B {
    // and here I want to use class A 's methoda,how can I do?
    thanks a lot

    Try the following. When run it eill print out:
    [In class C] A:B:C
    Now calling A's method: [In class A] A and i is 500Which is what you want right?
    public class TestSuperSuper {
        public static void main (String[] args) throws Exception {
            C c = new C();
            c.setName("A", "B", "C");
            c.setI(500);
            c.methodA();
        static class A {
            String aName;
            int i;
            public void methodA(){
                System.out.println("[In class A] " + aName + " and i is " + i);
            public void setName(String aName){
                this.aName = aName;
            public void setI(int i){
                this.i = i;
        static class B extends A {
            String bName;
            public void methodA(){
                System.out.println("[In class B] " + aName + ":" + bName);
            public void setName(String aName, String bName){
                this.aName = aName;
                this.bName = bName;
        static class C extends B {
            String cName;
            A wrappedA;
            public C(){
                wrappedA = new A();
            public void methodA(){
                reflectOnA();
                System.out.println("[In class C] " + aName + ":" + bName + ":" + cName);
                System.out.print("Now calling A's method: ");
                wrappedA.methodA();
            public void setName(String aName, String bName, String cName){
                this.aName = aName;
                this.bName = bName;
                this.cName = cName;
            private void reflectOnA(){
                try {
                Field[] aFields = wrappedA.getClass().getDeclaredFields();
                for (int i = 0; i < aFields.length; i++){
                    Class fldType = aFields.getType();
    if (fldType.isPrimitive()){
    if (fldType.getName().equals("int")){
    aFields[i].setInt(wrappedA, aFields[i].getInt(this));
    else {
    // now do the other primitive type tests here
    else {
    aFields[i].set(wrappedA, aFields[i].get(this));
    catch (Exception e){
    System.err.println(e);
    The main thing here is that in class C you have an instance variable called wrappedA which is an instance of A and the method called reflectOnA(). Basically, what this method does is it will set all the fields in wrappedA to the same values that this object has so that it would look like that wrappedA is somewhat the same as this object. You will call this method whenever you want to call your superclass' superclass' method.
    Hope this helps.

  • How to convert java class file version without decompiling

    Hi,
    Oracle R12.1.3 i am having illegal access error while try to access the class file version Java 1.3 uses major version 47,So how to convert the class file version without using decompiling.
    Current java version is 1.6.0_07
    Is there any tool or API for converting class file version?
    Thanks,
    Selvapandian T

    Beside this I wonder where you get your error from since AFAIK 12c comes with java 1.6.
    Well wonder no more!
    OP isn't using Oracle 12c database.
    They are using Oracle R12.1.3 - which is the E- Business Suite.

  • How to convert a class file to exe file and how to cteate a class file to d

    how to convert a class file to exe file

    Hi Bhaskarq,
    Hi,
    It is not at all possible.
    But it is a really worst method.
    Please go through it.
    This is a very common question asked in the comp.lang.java newsgroup. Its often useful to have an
    executable application when deploying your
    applications to a specific platform, but remember to
    make your .class files available for users running
    Unix/Macintosh/other platforms.
    Microsoft provide a free system development kit (SDK),
    for Java, which includes the jexegen tool. This
    will convert class files into a .EXE form. The only
    disadvantage is that users need a Microsoft Java
    Virtual Machine (JVM) installed. If your target
    platform is Win32, you can either redistribute the
    virtual
    machine, or raise the level of your system
    requirements, to include Windows 98, or Windows 95
    with
    Internet Explorer 4. Systems matching these
    requirements will already have a copy of the Microsoft
    Java Virtual Machine installed.
    Note : You must specify all of the class files your
    application needs (except for standard java packges)
    as a parameter, so if you have third party libraries,
    you'll need to include them as well. You can use wildcards * though, and you don't need the original source code.
    Also please see this Forum which will give a good idea
    http://forum.java.sun.com/thread.jsp?forum=31&thread=149733
    I hope this will help you.
    Thanks
    Bakrudeen
    Technical Support Engineer
    Sun MicroSystems Inc, India

Maybe you are looking for

  • How do I delete an app store app from my computer?

    I downloaded a useless app from the app store and I want to delete from my computer. Is there a way to do this? Thanks, Lou

  • Diferences with assets amounts after migration

    Hi Gurus!! We need your knowledge!! We found some diferences between asset balances (transaction S_ALR_87011964) and Financial Statement (transaction S_PL0_86000028) amounts after migrate to ECC6. We have read many notes and we havent found any solut

  • How to correct? Inserted pictures do not show in Mail programs.

    I can insert pictures into my Mail on Yahoo and they show. When I send them to another email address on Yahoo, the pictures are not there. However, they are there with IE. What do I need to change in Firefox?

  • DataSource lookup: where to put it ?

    Hi all, I have the following question: what's the most correct method for DataSource lookup in a Session Bean? I look it up in the setSessionContext method: DataSource ds; public void setSessionContext(SessionContext ctx) {  this.ctx = ctx; ds = (jav

  • Temporaryitems folder in cache- Can I delete it's contents?

    HI all, I'm just discovering that the Cache folder is the culprit in taking up most of my Disk space, as I always use an external hard drive for all of my content.  So--how do I delete the cache folder contents? I discovered that the largest folder i