Instanciation of nested class using Class.newInstance();

I am having a problem to instanciate a nested class using Class
new instance method. The problem is as follows:
class A {
public static class B {
String xxx;
class Instance {
public static void main ( String args []) {
String name = "A"
Class name_class = Class.forName(name);
Object name_object = name_class.newInstance();
Class [] in_classes = name_class.getClasses();
for (i =0; i < in_classes.length; i ++) {
Class inner = in_classes ;
System.out.println("class =" + inner.getName());
Here: Object inner_object = inner.newInstance();
An exception is thown at <Here> line where the newInstance is called
on nested class.
Anybody run into this problem, please help.
Thanks

Well, it seems to work for me :D
public class Test {
     public static void main ( String args []) {
          try {
               String name = "A";
               Class name_class = Class.forName(name);
               Object name_object = name_class.newInstance();
               Class [] in_classes = name_class.getClasses();
               for (int q =0; q < in_classes.length; ++q) {
                    Class inner = in_classes [q];
                    System.out.println("class =" + inner.getName());
                    A.B inner_object = (A.B) inner.newInstance();
                    System.out.println (inner_object.xxx);
          } catch (final Exception e) {
               e.printStackTrace ();
               System.out.println (e.getMessage ());
class A {
     public static class B {
          public String xxx = "Hi";
}

Similar Messages

  • When to use Nested Class/Inner Classes ?

    I am not very clear, when to use nested/inner classes..
    The scenario is :-
    class ABC
    //ABC need to store multiple instance of class XYZ
    class XYZ
    int member1;
    int member2;
    One approach is
    class ABC
    class XYZ
    //vector of class XYZ instances is stored in class-ABC
    or another approach is Class XYZ can be in separate JAVA file.
    Query:-
    1) Is there any difference between nested or Inner class...or are they same?
    2) When should they be used....Is it good to use in above scenario.
    3) What are the disadvtanges/advantages of using the Nested
    class.

    Query:-
    1) Is there any difference between nested or Inner
    class...or are they same?I really don't get it. Yes there is a difference between having an inner class, and a class in a separate file, but a nested class is an inner class.
    2) When should they be used....Is it good to use in
    above scenario.To write an inner class is a design decision. Do other classes need to know about the class XYZ or not? Do the XYZ class need to know about the inner working of the ABC class? How complex is the XYZ class etc.
    >
    3) What are the disadvtanges/advantages of using the
    Nested
    class.See above.
    /Kaj

  • How can you create an instance of a class using ClassLoader given only

    the class name as a String. I have the code below in the try block.
    Class myTest = this.getClass().getClassLoader().loadClass("Testclass");
    Object obj = myTest.newInstance();
    String className = obj.getClass().getName();I don't want to typecast the class like
    Testclass obj = (TestClass) myTest.newInstance();I want to be able to create the classs at runtime and then get the methods in the class and execute those methods. Can it be done without having to code the typecasting in before compile time?

    I read on the web of people creating objects from interfacesDoesn't sound like the thing to do... Theoretically you could create dummy classes on the fly that implement some interface, but that's not very useful.
    Sounds like you are trying to load classes and execute them via interfaces. Like this:
         Class clazz = Class.forName("java.util.LinkedList");
         Collection c = (Collection) clazz.newInstance();
         c.add("hello");
         c.add("world");
         System.out.println(Arrays.toString(c.toArray()));LinkedList is the class, Collection is the interface which LinkedList implements. You can then call the methods declared in the interface. The interface gets "compiled in" into the program and the classes that implement it get loaded whenever and from wherever you load them.
    You could also use reflection to call methods without an interface, but that is type-unsafe, inelegant, hackish, and just plain ugly.

  • Using Class and Constructor to create instances on the fly

    hi,
    i want to be able to create instances of classes as specified by the user of my application. i hold the class names as String objects in a LinkedList, check to see if the named class exists and then try and create an instance of it as follows.
    the problem im having is that the classes i want to create are held in a directory lower down the directory hierarchy than where the i called this code from.
    ie. the classes are held in "eccs/model/behaviours" but the VM looks for them in the eccs directory.
    i cannot move the desired classes to this folder for other reasons and if i try to give the Path name to Class.forName() it will not find them. instead i think it looks for a class called "eccs/model/behaviours/x" in the eccs dir and not navigate to the eccs/model/behaviours dir for the class x.
    any ideas please? heres my code for ye to look at in case im not making any sense:)
    //iterator is the Iterator of the LinkedList that holds all the names of the
    //classes we want to create.
    //while there is another element in the list.
    while(iterator.hasNext())
    //get the name of the class to create from the list.
    String className = (String) iterator.next();
    //check to see if the file exists.
    if(!doesFileExist(className))
    System.out.println("File cannot be found!");
    //breake the loop and move onto the next element in the list.
    continue;
    //create an empty class.
    Class dynamicClass = Class.forName(className);
    //get the default constructor of the class.
    Constructor constructor = dynamicClass.getConstructor(new Class[] {});
    //create an instance of the desired class.
    Behaviour beh = (Behaviour) constructor.newInstance(new Object[] {});
    private boolean doesFileExist(String fileName)
    //append .class to the file name.
    fileName += ".class";
    //get the file.
    File file = new File(fileName);
    //check if it exists.
    if(file.exists())
    return true;
    else
    return false;
    }

    ok ive changed it now to "eccs.model.behaviours" and it seems to work:) many thanks!!!
    by the following you mean that instead of using the method "doesFileExist(fileName)" i just catch the exception and throw it to something like the System.out.println() ?
    Why don't you simply try to call Class.forName() and catch the exception if it doesn't exist? Because as soon as you package up your class files in a jar file (which you should) your approach won't work at all.i dont think il be creating a JAR file as i want the user to be able to create his/her own classes and add them to the directory to be used in the application. is this the correct way to do this??
    again many thanks for ye're help:)

  • Subclassing nested (private ns) classes at runtime

    A question for the AVM2 engineers here.
    I am the author of
    asmock, a dynamic object
    mocking framework, and am looking at a few features to add before
    1.0. One of the biggest features I'd like to support is the ability
    to mock a "nested" (private namespace) class.
    I know that subclassing a nested class outside the "code
    file" is illegal, but I have assumed that the AVM will let me do it
    as long as I setup the DoABC tag correctly.
    Based on dumps of valid SWFs that do this, there does not
    seem to be anything special about the classes. Both the child and
    the parent are declared with a private ns multiname (0x05) and the
    members are declared as public traits of the class. The ns used is
    copied directly from the parent (for nested classes), and is always
    "Filename.as$number". However, during loadBytes, I get a
    ValidateError: "Class
    MockRepositoryNestedClassIntegrationFixture.as$452::NestedClass
    could not be found".
    Is there anything I might have missed? Or, alternatively, is
    there an explicit AVM restriction that nested classes can only be
    subclassed within the SWF they were loaded from?
    Many thanks,
    Richard

    "richard.szalay" <[email protected]> wrote
    in message
    news:gm3rfo$f0h$[email protected]..
    >A question for the AVM2 engineers here.
    >
    > I am the author of
    http://asmock.sourceforge.net/,
    a dynamic object
    > mocking
    > framework, and am looking at a few features to add
    before 1.0. One of the
    > biggest features I'd like to support is the ability to
    mock a "nested"
    > (private
    > namespace) class.
    >
    > I know that subclassing a nested class outside the "code
    file" is illegal,
    > but
    > I have assumed that the AVM will let me do it as long as
    I setup the DoABC
    > tag
    > correctly.
    >
    > Based on dumps of valid SWFs that do this, there does
    not seem to be
    > anything
    > special about the classes. Both the child and the parent
    are declared with
    > a
    > private ns multiname (0x05) and the members are declared
    as public traits
    > of
    > the class. The ns used is copied directly from the
    parent (for nested
    > classes),
    > and is always "Filename.as$number". However, during
    loadBytes, I get a
    > ValidateError: "Class
    >
    MockRepositoryNestedClassIntegrationFixture.as$452::NestedClass
    could not
    > be
    > found".
    >
    > Is there anything I might have missed? Or,
    alternatively, is there an
    > explicit
    > AVM restriction that nested classes can only be
    subclassed within the SWF
    > they
    > were loaded from?
    I think you're more likely to find someone who knows the
    framework and the
    player in this kind of detail on the flexcoders yahoo group.

  • How use class file in jsp(very urgent)

    i have class file called birds (birds is actually a xslt file transformed to java class file) now this class file i have to use in my jsp file. how can i use them. if possible can any one give me sample code please very urgent
    can any one help me

    java files
    import org.w3c.dom.*;
    import javax.servlet.http.*;
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    import java.io.*;
    public class XmlParser
         public String XmlParser()
              try
    String strXML= "employee.xml";
                   String xslFile = "employeeId.xsl";
                   TransformerFactory tFactory = TransformerFactory.newInstance();
                   StreamResult theTransformationResult = new StreamResult( new ByteArrayOutputStream() );
                   Transformer transformer = tFactory.newTransformer(new StreamSource(xslFile));
                   transformer.transform(new StreamSource(new StringReader(strXML)), theTransformationResult);
                   String output = theTransformationResult.getOutputStream().toString()
              catch(Exception e)
                   System.out.println(" ***** XmlParser.XmlParser ERROR ***** " + e);
    return output;
    using class files in jsp
    <%@ page import="com.qqqq.aaaa.XmlParser"%>
    <%
         XmlParser xmlParser          =     new XmlParser();
    out.println(xmlParser.XmlParser());
    %>
    i think it will help you.

  • How to create an object of our own class by using Class.forName()??

    how to create an object of our own class by using Class.forName()??
    plzz anser my qustion soon..

    Class.forName does not create an object. It returns a reference to the Class object that describes the metadata for the class in question--what methods and fields it has, etc.
    To create an object--regardless of whether it's your class or some other class--you could call newInstance on the Class object returned from Class.forName, BUT only if that class has a no-arg constructor that you want to call.
    Class<MyClass> clazz = Class.forName("com.mycompany.MyClass");
    MyClass mine = clazz.newInstance();If you want to use a constructor that takes parameters, you'll have to use java.lang.reflect.Constructor.
    Google for java reflection tutorial for more details.
    BUT reflection is often abused, and often employe when not needed. Why is it that you think you need this?

  • How to access private method of an inner class using reflection.

    Can somebody tell me that how can i access private method of an inner class using reflection.
    There is a scenario like
    class A
    class B
    private fun() {
    now i want to use method fun() of an inner class inside third class i.e "class c".
    Can i use reflection in someway to access this private method fun() in class c.

    I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
    Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
    So here's what it looks like:
            //list of inner classes, if any
            Class[] classlist = A.class.getDeclaredClasses();
            A outer = new A();
            try {
                for (int i =0; i < classlist.length; i++){
                    if (! classlist.getSimpleName().equals("B")){
    //skip other classes
    continue;
    //this is what I mention above.
    Constructor constr = classlist[i].getDeclaredConstructor(A.class);
    constr.setAccessible(true);
    Object inner = constr.newInstance(outer);
    Method meth = classlist[i].getDeclaredMethod("testMethod");
    meth.setAccessible(true);
    //the actual method call
    meth.invoke(inner);
    } catch (Exception e) {
    throw new RuntimeException(e);
    Good luck, and if you find yourself relying on this too much, it might mean a code redesign.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problems calling java classe using WSIF in BPEL 10.1.3.3

    Hi,
    I am working on a POC for a telecom gaint in Sweden. One of their requirement is to invoke java library.
    Inorder to do it, I have followed the below steps:
    1. Wrote a wrapper java code to a class in this library.(Attached with this mail)
    2. Using JDEV 10.1.3.3 created a wsdl file of WSIF binding type for invoking this wrapper class.(Attached with this mail.)
    3. Created the required fascade classes using the SCHEMAC option in command prompt.
    4. Placed all the class files including the wrapper class file in %BPELHOME%\bpel\system\classes
    5. Created a BPEL process to invoke the wsif wsdl.
    However while Invoking the BPEL process I am getting the error"com.collaxa.cube.ws.wsif.providers.java.WSIFOperation_Java@9ecad : Could not invoke 'authenticate'; nested exception is:
         org.collaxa.thirdparty.apache.wsif.WSIFException: No method named 'authenticate' found that match the parts specified"
    Can someone tell me how to resolve this issue.
    I have to do a presentation on this in 2 days.
    Thanks for the help.
    Regards,
    Gautham

    Hi in BPEL XML,
    Enter the credientials,
    I have pasted the Sample BPEL file.
    <?xml version="1.0"?>
    <BPELSuitcase>
         <BPELProcess id="BankTransferFlow" src="BankTransferFlow.bpel">
              <partnerLinkBindings>
                   <partnerLinkBinding name="client">
                        <property name="wsdlLocation">BankTransferFlow.wsdl</property>
                   </partnerLinkBinding>
                   <partnerLinkBinding name="bankTransfer">
                        <property name="wsdlLocation">BankTransferServiceDesign.wsdl</property>
                        <property name="wsdlRuntimeLocation">BankTransferService.wsdl</property>
                        <property name="java.naming.security.principal">oc4jadmin</property>
                        <property name="java.naming.security.credentials">welcome1</property>     
                        <property name="dedicated.connection">true</property>          
                   </partnerLinkBinding>
              </partnerLinkBindings>
    <configurations>
    <property name="testIntroduction"><![CDATA[
         This demo showcases the integration of session beans into
         an end-to-end business process. The database has 2 accounts 11111 and 22222 and both of them have initial balance 1000.
         ]]></property>
    <property name="defaultInput"><![CDATA[<BankTransferFlowRequest xmlns="http://samples.otn.com">
    <fromAccount>11111</fromAccount>
    <toAccount>22222</toAccount>
    <amount>10</amount>
    </BankTransferFlowRequest>
    ]]></property>
    <property name="transaction">participate</property>
    <property name="inMemoryOptimization">true</property>
    </configurations>          
         </BPELProcess>
    </BPELSuitcase>
    Thank you,
    [email protected]

  • Instantiation an inner class using reflection

    I want to instantiate an inner class using the Class.newInstance() method called within the Outer class constructor:
    public Outer
    public Outer()
    Inner.class.newInstance();
    private Class Inner { }
    When I try it, however, I get an InstantiationException.
    Is there some way to do this?
    Thanks for the help.
    Scott

    Here is a consolidation of what everyone posted and it does appear to work. In one of your post you used the getDeclaredConstructors() method and said it was less than ideal; I am not sure what you meant but I suspect it was the hard coded array reference. Anyhow I used the getDeclaredConstructor() method which appears to get non-public constructors also and is basically the same as using the getConstructor() method.
    import java.lang.reflect.*;
    public class Test35 {
        static public void main(String[] args) {
            Test35 t35 = new Test35();
            t35.testIt();
        private class Inner {
            public String toString() {
                return "Hear I am";
        public void testIt() {
            try {
                Constructor con = Inner.class.getDeclaredConstructor(new Class[] {Test35.class});
                Inner in = (Inner)con.newInstance(new Object[] {this});
                System.out.println(in);
            } catch (Exception e) {
                e.printStackTrace();

  • Instantiating object using Class.forName()

    What is the difference between instantiating using Class.forName() method and instantiating using the new operator?

    The difference is that you can use the new operator to instantiate an object, but you can't do it using Class.forName().
    But seriously folks...
    Presumably you're talking about Class.newInstance()--which often appears right on the heels of Class.forName().
    New gives you compile-time checks you don't get with Class.forName(). If it compiles with new, then you know the constructor in question exists on the class in question.
    With Class.newInstance() (and it's cousin (also called newInstance, I think) in the Constructor class), you can't be sure until you actually execute it whether that constructor even exists.
    New requires you to know the class at compile time. NewInstance lets you defer the specific class until runtime.
    New is simpler and more direct.
    (Did I just do your homwork for you? Hope not.)

  • 'USING CLASS LOADERS FOR HOT DEPLOYMENT' not working...

    Hi all, Im trying to use use the code from:
    http://developer.java.sun.com/developer/TechTips/2000/tt1027.html#tip3 to load reload classes that have changed meanwhile the main process was running. It doesn't work for me. When I write RELOAD, it doesn't reload the new .class generated and the result is the same than after generate the new .class file.
    Any ideas? Do you have tried this and it worked for you?
    Please help me.
    Thanks in advance.
    Dani.
    the code is:
    //file ServerItf.java
    public interface ServerItf {
    public String getQuote();
    //file Client.java
    import java.net.URL;
    import java.net.URLClassLoader;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    public class Client {
    static ClassLoader cl;
    static ServerItf server;
    public static void loadNewVersionOfServer()
    throws Exception {
    URL[] serverURLs =
    new URL[]{new URL("
                file:server/")};
    cl = new URLClassLoader(serverURLs);
    server = (ServerItf) cl.loadClass(
    "ServerImpl").newInstance();
    public static void test() throws Exception {
    BufferedReader br = new BufferedReader(
    new InputStreamReader(System.in));
    loadNewVersionOfServer();
    while (true) {
    System.out.print(
    "Enter QUOTE, RELOAD, GC, or
    QUIT: ");
    String cmdRead = br.readLine();
    String cmd = cmdRead.toUpperCase();
    if (cmd.equals("QUIT")) {
    return;
    } else if (cmd.equals("
    QUOTE")) {
    System.out.println(
    server.getQuote());
    } else if (cmd.equals("
    RELOAD")) {
    loadNewVersionOfServer();
    } else if (cmd.equals("
    GC")) {
    System.gc();
    System.runFinalization();
    public static void main(String [] args) {
    try {
    test();
    catch (Exception e) {
    e.printStackTrace();
    // file ServerImpl.java. Place this file
    // in a subdirectory named 'server'.
    class Reporter {
    Class cls;
    Reporter(Class cls) {
    this.cls = cls;
    System.out.println(
    "ServerImpl class " +
    cls.hashCode() +
    " loaded into VM");
    protected void finalize() {
    System.out.println("ServerImpl
    class " +
    cls.hashCode() + " unloaded
    from VM");
    public class ServerImpl implements ServerItf {
    //catch the class being unloaded from the VM
    static Object reporter =
    new Reporter(ServerImpl.class);
    public String getQuote() {
    return "A rolling stone gathers no
    moss";
    Compile the Client and ServerItf files in a directory, and then compile the ServerImpl in a subdirectory named "server." Make sure to include the higher level directory on your class path when you compile ServerImpl, for example:
    javac -classpath \mypath\ServerImpl.java
    When you start the Client, you should see the following prompt:
    Enter QUOTE, RELOAD, GC, or QUIT:
    Enter QUOTE to see the current quote from the server:
    A rolling stone gathers no moss
    Now, without shutting down the process, use another console or GUI to edit the ServerImpl class. Change the getQuote method to return a different quote, for example, "Wet birds do not fly at night." Recompile the server class. Then return to the console where the Client is still running and enter RELOAD. This invokes the method loadNewVersionOfServer(), which uses a new instance of URLClassLoader to load a new version of the server class. You should see something like this:
    ServerImpl class 7434986 loaded into VM
    Reissue the QUOTE command. You should now see your new version of the quote, for example:
    Wet birds do not fly at night

    http://forum.java.sun.com/thread.jsp?forum=4&thread=460822&tstart=0&trange=30

  • Can Class.forName("SomeClassName").newInstance() work in all classes?

    I saw some classes don't have a method called "newInstance()".
    but I have seen some advices say that is better using "Class.forName().newInstance()" than using "Class.forName()".

    I saw some classes don't have a method called
    "newInstance()".If you have class Foo, and you do Class.forName("Foo").newInstance();you're not calling Foo's newInstance method. You're calling java.lang.Class' newInstance method. You have a Class object that represents the Foo class. You tell that Class object newInstance() which invokes the public no-arg constructor of class Foo (as if you had done new Foo()). If Foo doesn't have a public no-arg constructor, you'll get an exception.
    but I have seen some advices say that is better using
    "Class.forName().newInstance()" than using
    "Class.forName()".They do two completely different things, and Class.forName().newInstance() first does Class.forName() and then class newInstance() on what that returns.
    Class.forName("Foo") returns the Class object that is associated with class Foo. It also loads the class if it hasn't already been loaded. It returns an instance of java.lang.class
    newInstance() calls the public, no-arg ctor of that class, if that ctor exists. Otherwise it throws an exeption. If it succeeds, it returns an instance of Foo.

  • Can I use classes and methods for a maintenance view events?

    Hello experts,
    Instead of perform/form, can I instead use classes and methods, etc for a given maintenance view event, lets say for example I want to use event '01' which is before saving records in the database. Help would be greatly appreciated. Thanks a lot guys!

    Hi viraylab,
    1. The architecture provided by maintenance view
       for using EVENTS and our own code inside it -
       It is provided using FORM/PERFORM
       concept only.
    2. At this stage,we cannot use classes.
    3. However, inside the FORM routine,
       we can write what ever we want.
       We can aswell use any abap code, including
       classes and methods.
      (But this classes and methods won't have any
       effect on the EVENT provided by maintenance view)
    regards,
    amit m.

  • How to place header and footer  in OO-ALV program using class

    How to place header and footer  in OO-ALV program using class tell me wat r the class we shold use and their attributes as well

    Hi Venkatesh,
    Take a look at this how to [ABAP Objects - ALV Model - Using Header and Footer|https://wiki.sdn.sap.com/wiki/x/xdw]
    it's explaining how to define the classes and use it for display an ALV with Header and Footer.
    Regards,
    Marcelo Ramos

Maybe you are looking for

  • Analog VIDEO OUT on G5?

    I use a deck with Firewire in and S-video out with Final Cut. Can I get my G5 to send a signal the same way for DVD's, etc? Thanks so much!

  • How to add a border around a video (padding out to a larger size)?

    Hi, I'm having problems doing this in Quicktime Pro. I don't want to increase the size of the visible part of the video, just pad it out with black space. I created a gif file of the size I want and pasted it in, but rather than the video increasing

  • How can I set trace on?  In the parameter config file

    I tried this trace traceoopts="trace_all" it didn't work. can you tell me how to set trace on in the configuration parameter file?

  • Just updated to 1.1 and cannot see edit icons in filmstrip

    Hello, in the middle of editing several hundred images and now that I updated to v1.1 I no longer see the icons in the filmstrip which indicate whether an image has been cropped or exposure adjustments have been made. I only see my star ratings. They

  • How to configure 9i Forms Services Demo Manually

    Hi, I want to customize the forms services demo and run from my own configuration file i mean instead of forms90demo.cfg file i want to create my own cfg file and run the forms how to do this? for example currently to run a demo i need to give the ur