get Class

Discussion in 'Java' started by Guest, Oct 28, 2004.

  1. Guest

    Guest Guest

    Can I get the Class of a class, without create an instance of that class?

    -----------
    class MyClass {
    }

    class A {
    public static int main(String[] argv) {
    MyClass mc = new MyClass();
    Class cls = mc.getClass();
    // I want something like:
    // Class cls = MyClass.getClass();
    Object obj = createAnInstanceOfAnyClass(cls);
    }

    public Object createAnInstanceOfAnyClass (Class cls) {
    return cls.newInstance();
    }
    }
    Guest, Oct 28, 2004
    #1
    1. Advertising

  2. "<- Chameleon ->" <> scribbled the following:
    > Can I get the Class of a class, without create an instance of that class?


    > -----------
    > class MyClass {
    > }


    Try MyClass.class.

    --
    /-- Joona Palaste () ------------- Finland --------\
    \-------------------------------------------------------- rules! --------/
    "Show me a good mouser and I'll show you a cat with bad breath."
    - Garfield
    Joona I Palaste, Oct 28, 2004
    #2
    1. Advertising

  3. <- Chameleon -> wrote:
    > Can I get the Class of a class, without create an instance of that class?


    You should be able to do this.
    Instead of object.getClass();
    use the Class.forName(String name_of_class);


    > // I want something like:
    > // Class cls = MyClass.getClass();
    > Object obj = createAnInstanceOfAnyClass(cls);
    > }
    >
    > public Object createAnInstanceOfAnyClass (Class cls) {
    > return cls.newInstance();
    > }
    > }


    By the way - your createAnInstanceOfAnyClass method will fail if the is
    no empty Constructor is found in the Class - so you might want to make a
    new instance upon a suitable Constructor from the Class instead.
    hal@no_spam_statsbiblioteket.dk, Oct 28, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?SG1udA==?=
    Replies:
    5
    Views:
    2,632
    IcingDeath
    Jun 25, 2006
  2. E11
    Replies:
    1
    Views:
    4,711
    Thomas Weidenfeller
    Oct 12, 2005
  3. christopher diggins
    Replies:
    16
    Views:
    731
    Pete Becker
    May 4, 2005
  4. Joseph Turian
    Replies:
    5
    Views:
    577
  5. svintuss
    Replies:
    3
    Views:
    88
    svintuss
    Nov 4, 2005
Loading...

Share This Page