java - a coding about reflection has a error "No enclosing instance of type student is accessible" -


here coding reflection:

public class student { private string name;  public student(){ this.name = "elodie";    } public string getname(){return name;}  class teacher { private string name; public teacher(){     this.name = "lady lee"; } public string getname() {     return name; } }  public static class reflect{ public static void main(string[] args) {student student = new student();  teacher teacher = new teacher();   system.out.println(student.getclass().getname() + " " + student.getname());  system.out.println(teacher.getclass().getname() + " " + teacher.getname()); } } } 

i got 1 error message "no enclosing instance of type student accessible. must qualify allocation enclosing instance of type student (e.g. x.new a() x instance of student)."

at teacher teacher = new teacher();

since want coding result like: student elodie teacher lady lee

so cannot write student.new teacher() if works.

btw, can explain bit reflection based on coding? know can use reflection info of other classes long know name of class.

the error you're getting because you're trying initialize instance of inner class.

the inner class can of 4 types:

  1. static
  2. method local
  3. anonymous
  4. other above these normal inner class

for more info on inner class, see link.

in code, you've used normal inner class. make instance of it, replace following:

teacher teacher = new teacher(); 

with following:

teacher teacher = student.new teacher(); 

in order desired result, replace following:

system.out.println(teacher.getclass().getname() + " " + teacher.getname()); 

with following:

system.out.println(teacher.getclass().getsimplename() + " " + teacher.getname()); 

as far reflection concerned, refer comment given vanza.

hope info helps you.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -