cancel
Showing results for 
Search instead for 
Did you mean: 

Instantiate inner class

Former Member
0 Kudos

Hi,

I need to instantiate inner class using exactly this class java.beans.Beans.instantiate().

[code]

import java.beans.Beans;

public class Test {

public static void main(String[] args) throws Exception{

// Class.forName("Test$Testinner");

// Testinner testinner = new Test().new Testinner();

Testinner testinner = (Testinner)Beans.instantiate(Test.class.getClassLoader(), "Test$Testinner");

System.out.println(testinner);

}

class Testinner{

private String value;

public String getValue() {

return value;

}

public void setValue(String value) {

this.value = value;

}

}

}

[/code]

However this code throws:

Exception in thread "main" java.lang.ClassNotFoundException: class Test$Testinner : java.lang.InstantiationException: Test$Testinner

at java.beans.Beans.instantiate(Beans.java:208)

at java.beans.Beans.instantiate(Beans.java:48)

at Test.main(Test.java:9)

Caused by: java.lang.InstantiationException: Test$Testinner

at java.lang.Class.newInstance0(Class.java:335)

at java.lang.Class.newInstance(Class.java:303)

at java.beans.Beans.instantiate(Beans.java:204)

... 2 more

Does anyone have a clue how can inner class be instantiated using Beans.instantiate?

Thanks in advance,

Todor

Accepted Solutions (0)

Answers (3)

Answers (3)

former_member182372
Active Contributor
0 Kudos

Hi Todor,

[code]import java.beans.Beans;

public class Test {

public static void main(String[] args) throws Exception{

Testinner testinner = (Testinner)Beans.instantiate(Test.class.getClassLoader(), "Test$Testinner");

System.out.println(testinner);

}

static public class Testinner {

private String value;

public Testinner() {}

public String getValue() {

return value;

}

public void setValue(String value) {

this.value = value;

}

}

}

[/code]

Best regards, Maksim Rashchynski.

0 Kudos

Hi Todor,

this can't work anyway since the inner class is not static. Instantiation of it requires an outer instance, therefore there will be no no-arg constructor even if you made the inner class public. The compiler adds silently a parameter for the outer class instance to each constructor of the inner class.

Regards

Richard

Former Member
0 Kudos

Hi Todor,

Sorry to say, but i think

Beans.instantiate

won't work for inner classes.

Read carefully the jdk api, i think you will get a clarity oin this, it says you the instatiating class should be in public context and should have a no-arguement contructor.

http://java.sun.com/j2se/1.4.2/docs/api/java/beans/package-summary.html

{ Read the <b>Long-Term Persistence</b> paragraph }

Hope this helps you.

Best regards,

Guru.

PS: Reward points for helpfull replies.