Problem instantiating static nested class
How come this doesn't work?
public class A {
public static class B {
public class Test {
A.B test = new A.B();
}The errors i got are:
-Not an enclosing class: A
-No enclosing instance of type A is in scope.
TIA
The code you posted compiled just fine for me.Ya you're right... stupid JBuilder failed me again; had to do a clean rebuild for JBuilder to recognize its not an error.
Similar Messages
-
Are static nested classes thread-safe?
There doesn't seem to be any definitive answer to this. Given the following code, is it thread-safe?
public class SomeMultiThreadedWebController {
public HttpServletResponse someMethodToExecuteViaWebRequest(HttpServletRequest request) {
simpleQueryBuilder("SELECT...").addParameter("asdf","asdf").createQuery(EMF.getEntityManager()).executeUpdate();
protected static class SimpleQueryBuilder {
private String queryString;
private Map<String, Object> params = new HashMap<String, Object>();
public SimpleQueryBuilder(String queryString) {
this.queryString = queryString;
public SimpleQueryBuilder addParameter(String name, Object value) {
params.put(name, value);
return this;
public Query createQuery(EntityManager em) {
Query query = em.createQuery(queryString);
for (Entry<String, Object> entry : params.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
return query;
public static SimpleQueryBuilder simpleQueryBuilder(String queryString) {
return new SimpleQueryBuilder(queryString);
}Forget whether or not someone would do this, as this is just an example. I'm really trying to get at whether or not the instance variables inside the static nested class are thread-safe. Thanks for any responses.Hello,
I believe you understand what you're talking about, but you state it in a way that is very confusing for others.
Let me correct this (essentially, incorrect uses of the terminology):
I agree that thread-safe or not is for an operation, for a member, it has some sort of contextual confusion.
Member has a much broader meaning in the [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4] . Even "class member" applies to both an attribute, a method, or an inner class or interface.
I think you mean "member variable" of a class (aka "attribute" or "field"). By the way, static or not is irrelevant to the rest of the discussion.
For an operation or a member, if there's only one thread could access it atomically in one moment, we could call it thread-safe.Mmm. I was tempted to say yes (I'm reluctant to commit myself). With an emphasis on "_The encapsulating class_ makes this member's usage thread-safe".
Still, just synchronizing each operation on a member is not enough to make all usages "thread-safe":
Consider a java.util.Vector: each add/get is synchronized, so it is atomic, fine.
However if one thread adds several values, let's say 3, one by one, to a vector that initially contains 0 values, and another thread reads the vector's size() (another properly synchronized method), the reader thread may witness a size anywhere among 0, 1, 2, 3, which, depending on the business logic, may be a severely inconsistent state.
The client code would have to make extra work (e.g. synchronizing on the vector's reference before the 3 adds) to guarantee that the usage is thread-safe.
Thus any synchronized method(With the limit stated above)
or immutable member (like primitive type) are thread-safe.
Additionally for a member, if it's immutable, then it's thread-safe. You mean, immutable primitive type, or immutable object. As stated previously, an immutable reference to a mutable object isn't thread-safe.
a static final HashMap still have thread-safe issue in practice because it's not a primitive.The underlined part is incorrect. A primitive may have thread-safety issues (unless it's immutable), and an object may not have such issues, depending on a number of factors.
The put, get methods, which will be invoked probably, are not thread-safe although the reference to map is.Yes. And even if the put/get methods were synchronized, the client code could see consistency issues in a concurrent scenario, as demonstrated above.
Additional considerations:
1) read/write of primitive types are not necessarily atomic: section [ §17.7 of the JLS|http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7] explicitly states that writing a long or double value (2 32-bits words) may not be atomic, and may be subject to consistency issues in a concurrent scenario.
2) The Java Memory Model explicitly allows non-synchronized operations on non-volatile fields to be implemented in a "thread-unsafe" way by the JVM. Leading way to a lot of unintuitive problems such as the "Double-Checked Locking idiom is broken". Don't make clever guess on code execution path unless you properly synchronize access to variables across threads.
Edited by: jduprez on Mar 4, 2010 9:53 AM -
Instantiating a nested class from JNI
Im able to instantiate my public member class "Inner" as long as the constructor does not take any arguments. If it requires arguments in the constructor, I get a crash report. I need to be able to instantiate the object with supplied initial arguments. Is this a bug in the JVM? Any suggestions?
/dan
Crash report follows after code:
class HelloWorld {
public class Inner {
private int myValue = 50;
public Inner() {}
public Inner(int myValue) {
this.myValue = myValue;
public Inner(int myValue, int there) {
this.myValue = myValue;
}C++ library:
jclass inr_clz = env->FindClass("LHelloWorld$Inner;");
if (inr_clz == NULL) {
return -25; // failed to find the class
// mid = env->GetMethodID(inr_clz, "<init>", "(LHelloWorld;)V"); // works
mid = env->GetMethodID(inr_clz, "<init>", "(LHelloWorld;II)V"); // also works
if (mid == NULL) {
return -30; // failed to get method
jint value = 400;
// inner = env->NewObject(inr_clz, mid); // works
inner = env->NewObject(inr_clz, mid, value, value); // crash here
if (inner == NULL) {
return -40; // out of memory error
...Crash message:
# An unexpected error has been detected by HotSpot Virtual Machine:
# Internal Error (53484152454432554E54494D450E43505001A3), pid=2008, tid=2628
# Java VM: Java HotSpot(TM) Client VM (1.5.0_06-b05 mixed mode)
# An error report file with more information is saved as hs_err_pid2008.log
# If you would like to submit a bug report, please visit:
# http://java.sun.com/webapps/bugreport/crash.jsp
#Im able to instantiate my public member class "Inner"
as long as the constructor does not take any
arguments. If it requires arguments in the
constructor, I get a crash report. I need to be able
to instantiate the object with supplied initial
arguments. Is this a bug in the JVM? Any
suggestions?It's your code.
Here's a working example:
==================
public class NativeInnerTest {
public static void main(String[] args) {
new Outer().doNative();
public class Outer {
static {
System.loadLibrary("outer");
public class Inner {
private int val;
Inner (int val) {
this.val = val;
public void foo() {
System.out.println("Value is: " + val);
public native void doNative();
}=====Native Code======================
#include "Outer.h"
JNIEXPORT void JNICALL Java_Outer_doNative (JNIEnv *env, jobject obj) {
jclass clz = env->FindClass("Outer$Inner");
if (clz == NULL) {
printf("Failed to find class Outer$Inner");
return;
jmethodID mid = env->GetMethodID(clz,"<init>", "(LOuter;I)V");
if (mid == NULL) {
printf ("Failed to find Inner constructor\n");
return;
jint val = 42;
jobject inner = env->NewObject(clz,mid,obj,val);
if (inner == NULL) {
printf ("Failed to construct Inner object\n");
return;
jmethodID fooID = env->GetMethodID(clz, "foo", "()V");
if (fooID == NULL) {
printf ("Failed to find method id for foo()\n");
return;
env->CallVoidMethod(inner, fooID);
}================================
The problem in your code is twofold. First, your type signature in the call to GetMethodID is incorrect. An inner class constructor taking a single integer argument should have a type signature like this:
(LHelloWorld;I)V
You can get the proper type signatures using the 'javap' tool. For my example, the output of javap looks like this:
[jim@daisy tmp]$ /usr/java/jdk1.6.0/bin/javap -s -private Outer.Inner
Compiled from "Outer.java"
public class Outer$Inner extends java.lang.Object{
private int val;
Signature: I
final Outer this$0;
Signature: LOuter;
Outer$Inner(Outer, int);
Signature: (LOuter;I)V
public void foo();
Signature: ()V
}Second, your call to NewObject does not have the proper parameter types. Here's your code:
inner = env->NewObject(inr_clz, mid, value, value);The corresponding correct line from my example is:
jobject inner = env->NewObject(clz,mid,obj,val);The constructor expects a 'HelloWorld' object and an integer as denoted in the correct
type signature.
You are passing in the integer 'val' twice when you should be doing something like this:
inner = env->NewObject(inr_clz, mid, obj, value);where 'obj' is the jobject passed to you by the VM along with the JNIEnv pointer. This jobject represents the instance of the enclosing class which every non static nested class must have.
Jim S. -
Hi there.
Im playing around with static nested classes:
class OuterC {
int x = 10;
static class Nest {
void doStuff() {
System.out.println("Going");
//System.out.println("Should be allowed print: " + x);
doOtherStuff();
public void doOtherStuff() {
System.out.println("Doing Stuff!");
public class Test {
static class OtherNest {
void arbitraryMethod() {
System.out.println("Going to do arbitrary stuff...");
public static void main(String[] args) {
OuterC.Nest n = new OuterC.Nest();
n.doStuff();
OtherNest on = new OtherNest();
on.arbitraryMethod();
}//close TestWhen I uncomment the statement to print out the instance variable x of class OuterC
I get a "cannot access non-static..." error, which is fine. I expect that.
But why can I run the doOtherStuff() method from the static nested class Nest?
doOtherStuff() is after all an instance method...
Many Thanks & regards!
Edited by: Boeing-737 on May 29, 2008 10:27 AM
Dont bother replying, I see the error now. The method is defined as a member within the nested
class. Apologies, I didn't spot that. My mistake.
Thanks.
Edited by: Boeing-737 on May 29, 2008 10:28 AMFrom the JLS, chapter 8:
A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
So "nested" iff "not top level".From the JLS, chapter 8:
An inner class is a nested class that is not explicitly or implicitly declared static.
So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
~ -
Static nested class VS non-static nested class ??
we know static method can be called without creating an object and static variables are shared among objects.
what is the difference between static nested class and non-static nested class ? When do we use them? what is the advantages of static nested class over non-static nested class in term of performance?From the JLS, chapter 8:
A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
So "nested" iff "not top level".From the JLS, chapter 8:
An inner class is a nested class that is not explicitly or implicitly declared static.
So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
~ -
Why a static nested class instead of a static block?
What difference does it make: using a static nested class on a static block?
Surya-2010 wrote:
What difference does it make: using a static nested class on a static block?Do you mean static initialization block?
They're different concepts. A static initialization block is part of the construction machinery of a class. A static nested class is a class you want to treat as part of another class. -
Hi everyone,
I'm practicing nested classes. I've written this simple class:
public class OuterClass {
private static class InnerClass {
private InnerClass() {
System.out.println("in constructor" }
} and another simple class to test:
public class TestClass {
public static void main(String[] args) {
OuterClass.InnerClass in= new OuterClass.InnerClass();
}All classes compile and main method runs with no problem. Now I wonder what is the meaning of the private modifier here ??
ThanksOk, I'm using Oracle's JDeveloper 3.2 ( jdk1.2.2). The code I posted compiles and runs with no errors in Jdeveloper.
However, I tested this on the command line ( using javac directly ) and it does not compile ! -
Problems instantiating oracle xdk class CXmlCtx
I'm having problems using the CXmlCtx C++ class in XDK 10g when I define my own ErrorHandler class. The default version appears to be working but does not allow any errors to be dealt with properly.
I believe there is some kind of memory corruption occurring as I'm getting inconsistent results when I instantiate CXmlCtx. There are times when the CXmlCtx class is instantiated and then I can successfully parse an xml doc BUT most of the time I'm getting a mix between Error 19 returned (which is XMLERR_PROP_NOT_FOUND) and a core dump.
Does anyone know what error 19 actually means and more importantly how can I avoid it? (and hopefully the core dumps).Hi,
I am facing a similar problem. Please let me know if you were able to resolve this/ -
Nested Classes and Static Methods
I was perusing the Java Tutorials on Nested Classes and I came across this...
[http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
int i;
static class Bar {
int j = i; // WRONG! Bar class is static context
}~ -
Nested classes and separate files in Javadoc...
Hello. I am writing an application, and it has several .java files, and some of the classes contained therein contain nested classes, for example
ClassOne.java
class ClassOne
// stuff
class innerClassOne
//more stuff
}ClassTwo.java
class ClassTwo
// stuff
class innerClassTwo
//more stuff
}What I want to do is generate documentation like the online java documentation for my app, that is, documentation that will contain ALL the classes and nested classes involved, and link everything that comes in java already to the sun online java docs.
I've figured out the -link command for javadoc, and I can make that work, but I've run into some other snags.
1.) Javadoc isn't finding or documenting my nested classes, despite them being marked up. Google does not wish to help.
2.) Some classes reference other classes of mine that aren't conatined in the same .java file, but do exist in their own .java files in the dame local directory. Javadoc does not like this, and gives errors.
3.) Running javadoc on one file at a time overwrites the old file's documentation, thus I cannot seem to get an index.html javadoc file that links to all my classes, nor can I get the classes to link to each other.
What do I need to do to fix these?So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
int i;
static class Bar {
int j = i; // WRONG! Bar class is static context
}~ -
Questions concerning Nested Classes
Hi!
Just read some articles about nested classes (include the ones from the Java Tutorial and the Effective Java chapter), and while most of it is perfectly clear, three questions remain:
1.) When I declare a member class, how should I declare the access specifiers (private, protected etc.) for the member class's attributes and methods? If I declare a member class as private, anything but private for the attributes and methods wouldn't make sense, would it?
2.) The Java Tutorial says:
Also, because an inner class is associated with an instance, it cannot define any static members itself.While this is true for static methods, it seems to be possible to declare static variables inside inner classes. This is confusing me... does it actually make sense to declare static variables inside inner classes (or member classes in general)? Or should the be placed in the declaring class?
3.) Another confusing quote from the Java Tutorial:
Static nested classes do not have access to other members of the enclosing class.This is true for instance variables and methods but not for static variables, which are also members of the enclosing class, aren't they?
Thanks in advance,
OIiverTrollhorn wrote:
Hi!
Just read some articles about nested classes (include the ones from the Java Tutorial and the Effective Java chapter), and while most of it is perfectly clear, three questions remain:
1.) When I declare a member class, how should I declare the access specifiers (private, protected etc.) for the member class's attributes and methods? If I declare a member class as private, anything but private for the attributes and methods wouldn't make sense, would it?
private static class MyInner implements Runnable
@Override public void run() // Must be public!
2.) The Java Tutorial says:
Also, because an inner class is associated with an instance, it cannot define any static members itself.While this is true for static methods, it seems to be possible to declare static variables inside inner classes. This is confusing me... does it actually make sense to declare static variables inside inner classes (or member classes in general)? Or should the be placed in the declaring class?Wrong. It can define static final member variables and I see no reason to move them to the outer class, if they are used only by the inner class.
3.) Another confusing quote from the Java Tutorial:
Static nested classes do not have access to other members of the enclosing class.This is true for instance variables and methods but not for static variables, which are also members of the enclosing class, aren't they?I agree with you here.
Edited by: baftos on Jun 6, 2009 9:18 AM -
JIT compiler and nested classes
Q1. how does JIT compile on fly and improve the performance ?
Q2. how is system.out.println(argument) implemented in java ? is it that system is a class in which out is a static nested class and println is a static method in out?Hello rishiluvsjava,
Q1. How does JIT compile on fly and improve the performance?
The following answer was taken from "The Java HotSpot Performance Engine Architecure: A White Paper About Sun's Second Generation Performance Technology" to view the full document go to:
http://java.sun.com/products/hotspot/whitepaper.html
Just-In-Time (JIT) compilers are essentially fast traditional compilers that translate the Java-technology bytecodes into native machine code on-the-fly. A JIT runs on the end-user's machine which actually executes the bytecodes, and compiles each method the first time it is executed.
Q2. How is System.out.println(argument) implemented in java ? is it that system is a class in which out is a static nested class and println is a static method in out?
From the Java docs:
System is a public final class in the java.lang package. It has three fields:
static PrintStream err // The "standard" error output stream.
static InputStream in // The "standard" input stream.
static PrintStream out //The "standard" output stream.println is one of the methods in the java.io.PrintStream class.
-Merwyn,
Developer Technical Support,
http://www.sun.com/developers/support. -
Could someone tell me what the rules of accessibility are for static and non-static inner classes being able to access elements of the enclosing class
A non-static or inner class can access all of the enclosing class's members, including private members. This is because each instance of an inner class is associated with an instance of the outer class, and inner classes are not allowed to have static members except for constants.
A static nested class can access only the static members of the enclosing class. This is because instances of the nested class are not associated with instances of the outer class. -
About static member class?
I can unstand the technical detail about static member class. But i still have a question about it.The questionis when shall we use it when we design a poject. In another word, in which situation, static member class will show its advantage? Thanks a lot.
http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=static+nested+class&col=javaforums
-
class A{
static class B{
public void instanceMethod()
System.out.println("instance method");
class C{}How do I access the instanceMethod() of class B from class C ?But what does new A.B() mean.Static means that
doesent run inside any instance of the class, rather it runs with class
itself. So shouldnt it have been just A.new B()
No, a static nested class is just a static member of the outer class.
All other static members are accessible as Outer.innerMember and
just so with that static nested class. Your proposal:A.new B()doesn't make sense because 'new' is not a static
member of outer class A.
kind regards,
Jos
Maybe you are looking for
-
Error while deleting the application deployed in WLS10.3
Hi everyone , I have installed WLS10.3 on a AIX box , and deployed a .ear file and a .rar file . When i try to stop them and then attempt to delete the file a error is thrown . However this error is not thrown consistently. Would be really glad if i
-
Adobe Tv. Problem Viewing Video
What I meant was that in Adobe Tv, When I click any Premiere cs5 tutorial like getting started or GS-01 or any other clip it loads the screen for the episode but the screen stays black without any way to play the clip. That is, the screen stays blac
-
Firefox 4 lost my bookmarks sidebar, started my home page with Yahoo finance in a strange place on Yahoo and generally gave me fits. I ran the install on an earlier version of Firefox which works great after I click on an error message eight times to
-
I have problem about starting SAP system. I executed stopsap command. After that I rebooted the HPUX system. And I try to execute startsap command.System gives me message below. brckxits:bxdadm 22> startsap Checking ORC Database ABAP Database is not
-
When creating a PDF of a MSWord document in File>Print>Save as PDF, the document gets saved correctly, but when added as an attachment to an email the entire document appears, not just the Adobe logo, as was always the case earlier. I've tried testin