problem about inner-classes-Collection of common programming errors


  • Eric B.
    java reflection field inner-classes
    I’m running into a strange result here and am not sure if it is a bug in Java or it is expected behaviour. I have an inner class on which I’ve used reflection to get the declared fields (class.getDeclaredFields()). However, when I loop over the list of fields and check the individual types, the “this” field returns the outerclass and not the inner class.Is this expected behaviour? It seems quite odd to me.Ex:import java.lang.reflect.Field;public class OuterClass {public class InnerClass{publi

  • johnny
    java inner-classes
    Are inner classes commonly used in Java? Are these the same as nested classes? Or have these been replaced in Java by something better? I have a book on version 5 and it has an example using an inner class, but I thought I read somewere that inner classes were “bad.”I have no idea and was hoping for thoughts on it.Thank you.

  • bestsss

  • KLibby
    java memory-management jvm inner-classes callstack
    In the following code:public class Main {Emp globalEmp;public void aMethod(){final int stackVar = 10;globalEmp = new Emp(){public void doSomeThing(){System.out.println(“stackVar :” + stackVar);}};}public static void main(String[] args){Main m = new Main();m.aMethod();m.globalEmp.doSomeThing();} }interface Emp{public void doSomeThing(); }As I can understand the following will be executed:Main m = new Main(); : A new Instance of the Main class will be created, with globalEmp set to null. m.aMethod

  • martsraits
    java reflection visibility inner-classes
    I have two compilation units:public class OuterClass{private static class InnerClass{public String test(){return “testing123”;}}public static void main( String[] args ){new CallingClass().test( new InnerClass() );} }public class CallingClass{public void test( Object o ){try{Method m = o.getClass().getMethod( “test” );Object response = m.invoke( o );System.out.println( “response: ” + response );}catch( Exception e ){e.printStackTrace();}} }If they are in the same package, everything works and “re

  • Erik Schierboom
    java inner-classes
    final JTextField jtfContent = new JTextField(); btnOK.addActionListener(new java.awt.event.ActionListener(){public void actionPerformed(java.awt.event.ActionEvent event){jtfContent.setText(“I am OK”);} } );If I omit final, I see the error “Cannot refer to a non-final variable jtfContent inside an inner class defined in a different method”.Why must an anonymous inner class require the outer classes instance variable to be final in order to access it?

  • Valtteri
    java swing gui inner-classes
    Some time ago I wrote a little image viewer/processing program with Java, a mini-Photoshop, if you will. I wanted there to be a drop-down menu where I could select which one of the images I have opened would be “on the table”, ie. shown and methods applied to. I wanted the name of the image to be the name of the JMenuItem shown in the menu. I also wanted a new button to appear when I add a new image.I wondered this for some time and finally produced this solution, a new class that handles the

  • ferrerverck
    java enums inner-classes instance-variables
    As I understood inner enums are always explicitly ?r implicitly static in java. Which means I can’t access instance fields from my inner enum class.public class InnerEnum {private enum SomeInnerEnum {VALUE1() {@Overridepublic void doSomething() {// ERROR: WON’T COMPILE// Cannot make static reference// to non-static field iSystem.out.println(i);}},VALUE2() {@Overridepublic void doSomething() {// do something else with i }};public abstract void doSomething();}private int i = 10; }I have found it p

  • dogbane
    java generics casting inner-classes
    Consider the following code:public class Outer<T> {public class Inner{}public static <T> Outer<T>.Inner get(){Object o = new Object();return (Outer<T>.Inner)o;}public static void main(String[] args) throws Exception {Outer.<String>get();} }This code compiles successfully in Eclipse, but fails to compile in javac:Outer.java:10: ‘)’ expectedreturn (Outer<T>.Inner)o;^ Outer.java:10: ‘;’ expectedreturn (Outer<T>.Inner)o;^ Outer.java:10: illegal start of exp

  • Brian
    java inheritance inner-classes private-methods
    Let’s take the following code:public class Test {class A {public A() {}private void testMethod() {System.out.println(“A”);}}class B extends A {public B() { super(); }private void testMethod() {System.out.println(“B”);}}public Test() { }public A get() {return new B();}public static void main(String[] args) {new Test().get().testMethod();} }I would expect that code to write B. A is written instead.It may feel weird (at least to me) the fact that a class can call private methods of the inner classe

  • Eto Demerzel
    java json serialization inner-classes jackson
    I have a question concerning Json deserialization using Jackson. I would like to deserialize a Json file using a class like this one: (taken from http://wiki.fasterxml.com/JacksonInFiveMinutes)public class User {public enum Gender { MALE, FEMALE };public static class Name {private String _first, _last;public String getFirst() { return _first; }public String getLast() { return _last; }public void setFirst(String s) { _first = s; }public void setLast(String s) { _last = s; }}private Gender _gende

  • java.is.for.desktop
    java reflection inner-classes anonymous-class
    I have an anonymous inner class inside another class (SomeClass).Both SomeClass.class.getClasses() and SomeClass.class.getDeclaredClasses() return empty arrays.I couldn’t find some hints on this in Class’ Javadocs.Can anonymous inner classes be retrieved using reflection in some way?What else are notable differences between anonymous inner classes and normal inner classes?

  • perez
    java inner-classes instanceof
    I coded in NetBeans something like this:public class Grafo<V, E> {class Par{int a, b;Par(int a, int b) {this.a = a;this.b = b;}@Overridepublic boolean equals(Object ob){if(ob instanceof Par) {Par p = (Par)ob;return this.a==p.a && this.b==p.b;}return false;}}//stuff… } //end of class GrafoThe error is in the method equals() from inner class “Par”.NetBeans says that the error is “illegal generic type of instanceof”. The error is in the line below.if(ob instanceof Par) {What is the

  • crazy horse
    java inner-classes static-initialization
    Context: java.io.File class has a static inner class method as follows:LazyInitialization.temporaryDirectory();[EDITED to add some more code] My code below eventually calls the above line of code. An exception is thrown from within the temporaryDirectory() method, which in my context is fine/expected.try {File tempFile = File.createTempFile(“aaa”, “aaa”); } catch (Exception e) {// handle exception }Then, when I next invoke the same method (createTempFile) again, I get a “java.lang.NoClassDefFou

  • toriscope
    java runtime classloader inner-classes class-loading
    I have a program where I compile java code that somebody writes in a text box, and run it. They type out the full source code, class and allI save the class they write to a random java source file, and then compile and load the class through a classloader. This works perfectly.I have a new issue though, that of sub classes. I give the outer class a unique name, and load that class.Ex.TEMP1110.java -> TEMP1110.class, etc. With inner classes, it compiles to TEMP1110$InnerClass.class I try loadi

  • Leoa
    android static context inner-classes android-gcm
    I’m trying to get the context of FragmentStackSupport Activity and use it in an inner static class. I’ve instantiated FragmentStackSupport in the inner static class and I’m using getBaseContext() to get the context of FragmentStackSupport. Putting the outer class context inside GCMRegistar.checkDevice(thisContext) does not give an error in the code but crashes the application. I can’t use ‘this’ or FragmentStackSupport.this because the inner class is static. “this” would work if the class was pu

  • user881667
    java android android-asynctask inner-classes
    I hope I explained this issue correctly in the title. I have some inner classes that extend AsyncTask to read some JSON data and parse it. I have two separate ones for each search query the user makes. Once I have the two separate results I want to do stuff with them in the same method. My thought was to use a variable argument method and in the onPostExecute of each individual AsyncTask send the result to that method. Not sure if this is the right way to go about it as the app is crashing on se

  • Jonathan Edwards
    php class mysqli inner-classes prepare
    there has been a similar topic (How to access mysqli connection in another class on another page?) but it doesn’t quite answer my question, or I’m missing the point. I’m trying to build a class which will allow me to quickly build the bones of a slideshow by pulling a set of image urls and div ids from a database. Here’s what I’ve managed:class make_slide {private $slide_mysqli;public $get_slide;public $single_slide;public $get_imgurl1; public $get_imgurl2; public $get_imgurl3; public $get_img

  • user1494396
    java inner-classes scriptengine
    I have a class that I can’t change as follows:public class Foo {public final int ID=0;public int bar;public final Object baz=null; }I want to have an anonymous inner class that overrides Foo such as:public Foo newFoo(final int mID, final int mbar, final Object mbaz) {return new Foo(){public final int ID = mID;public int bar = mbar;public final Object baz = mbaz;}; }I then have a javax.script.ScriptEngine that I want to call something like this in JS: newFoo(0,0,undefined)[“ID”]My problem is that

  • The New Idiot
    java inner-classes
    Why is the following piece of code not working? import java.util.Comparator;public class TestInner {public static void main(String[] args) {Comparator<String> comp = new Comparator<String>(){private String sample = null;@Overridepublic int compare(String arg0, String arg1) {// TODO Auto-generated method stubreturn arg0.compareTo(arg1);}public void setText(String t1){sample = t1;}};// compiler error – Method is undefined for the type Comparator<String> comp.setText(“xyz”); }}I h

  • Ken
    java javascript subclass rhino inner-classes
    I’m trying to subclass an inner class (defined in Java) in Rhino, and I can’t seem to make it work.I’ve got some compiled Java code (which I essentially can’t change) that has an inner abstract class:package mypackage; class MyClass {abstract static class MyInnerClass {abstract void print(String s);} }From Rhino, I can see it just fine:js> Packages.mypackage.MyClass.MyInnerClass [JavaClass mypackage.MyClass$MyInnerClass]But I can’t figure out how to subclass it. I figured something like this

  • rampion
    java ruby jruby inner-classes
    So given the following java class:class Outer {private int x;public Outer(int x) { this.x = x; }public class Inner{private int y;public Inner(int y) { this.y = y; }public int sum() { return x + y; }} }I can create an instance of the inner class from Java in the following manner:Outer o = new Outer(1); Outer.Inner i = o.new Inner(2);However, I can’t seem how to do the same from JRuby#!/usr/bin/env jruby require ‘java’ java_import ‘Outer’o = Outer.new(1); i = o.Inner.new(2); #=> NoMethodError:

  • Jarrod Roberson
    java enums constructor inner-classes type-erasure
    public enum Days {SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;public enum WeekDays{MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,}public enum WeekEnds{SATURDAY,SUNDAY;} }public class InnerEnumTestClass<E extends Enum<E>> {public E enumtype;/*** @param enumtype*/public InnerEnumTestClass(E enumtype) {super();this.enumtype = enumtype;}/*** @param args*/public static void main(String[] args) {InnerEnumTestClass<Days> testObj = new InnerEnumTestClass<Days>(Days.WeekDa

  • Svante
    java inner-classes java1.4
    When passing a final object (A String in the code below) it shows up as null when printed from the anonymous inner class. However, when a final value type or straight final String is passed in, its value is correctly displayed. What does final really mean in context of the anonymous inner class and why is the object passed null?public class WeirdInners {public class InnerThing{public InnerThing(){print();}public void print(){}}public WeirdInners(){final String aString = “argh!”.toString();fina

  • Nicola Peluchetti
    javascript dom inner-classes javascript-objects
    I am newbie to javascript objects and I have a problem. I am trying to make an image gallery but I keep getting an error that this.current, this.size & this.initial are undefined, and therefore, the script cannot work. Please help me resolve this error. the following is the full script.function gallery() {this.image = new Array(10);this.initial = 1; this.current = 0;this.size = 10;this.frame_height = 400;this.frame_width = 600;this.initialize=function(){if(document.images){var count = 1;fo

Web site is in building