Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding a private method

 
Jerri Combs
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to override a private method using reflection?
I know how to invoke a private method, and I know how to get or set the value of a private variable, but I want to override the method.

I want the main method in SubClass to print out 2, but it prints out 1.
I don't think this can be done through reflection.
If not, does anyone know of another way of doing it?
(Other than making SuperClass.getInt() protected, or copying and pasting the printInt() method into SubClass.)
 
Henry Wong
author
Marshal
Pie
Posts: 21115
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
slow grammer wrote:Is it possible to override a private method using reflection?
I know how to invoke a private method, and I know how to get or set the value of a private variable, but I want to override the method.

I want the main method in SubClass to print out 2, but it prints out 1.
I don't think this can be done through reflection.
If not, does anyone know of another way of doing it?
(Other than making SuperClass.getInt() protected, or copying and pasting the printInt() method into SubClass.)


Unfortunately, one of the requirements of overriding is that the superclass method must be accessible from the subclass -- so, besides the options that you already named, I don't think so.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic