How to access private method of an inner class using reflection.

Can somebody tell me that how can i access private method of an inner class using reflection.
There is a scenario like
class A
class B
private fun() {
now i want to use method fun() of an inner class inside third class i.e "class c".
Can i use reflection in someway to access this private method fun() in class c.

I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
So here's what it looks like:
        //list of inner classes, if any
        Class[] classlist = A.class.getDeclaredClasses();
        A outer = new A();
        try {
            for (int i =0; i < classlist.length; i++){
                if (! classlist.getSimpleName().equals("B")){
//skip other classes
continue;
//this is what I mention above.
Constructor constr = classlist[i].getDeclaredConstructor(A.class);
constr.setAccessible(true);
Object inner = constr.newInstance(outer);
Method meth = classlist[i].getDeclaredMethod("testMethod");
meth.setAccessible(true);
//the actual method call
meth.invoke(inner);
} catch (Exception e) {
throw new RuntimeException(e);
Good luck, and if you find yourself relying on this too much, it might mean a code redesign.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • How to call a method from a separate class using IBAction

    I can't work out how to call a method form an external class with IBAction.
    //This Works 1
    -(void)addCard:(MyiCards *)card{
    [card insertNewCardIntoDatabase];
    //This works 2
    -(IBAction) addNewCard:(id)sender{
    //stuff -- I want to call [card insertNewCardIntoDatabase];
    I have tried tons of stuff here, but nothing is working. When i build this I get no errors or warnings, but trying to call the method in anyway other that what is there, i get errors.

    Can you explain more about what you are trying to do? IBAction is just a 'hint' to Interface Builder. It's just a void method return. And it's unclear what method is where from your code snippet below. is addNewCard: in another class? And if so, does it have a reference to the 'card' object you are sending the 'insertNewCardIntoDatabase' message? Some more details would help.
    Cheers,
    George

  • Instantiation an inner class using reflection

    I want to instantiate an inner class using the Class.newInstance() method called within the Outer class constructor:
    public Outer
    public Outer()
    Inner.class.newInstance();
    private Class Inner { }
    When I try it, however, I get an InstantiationException.
    Is there some way to do this?
    Thanks for the help.
    Scott

    Here is a consolidation of what everyone posted and it does appear to work. In one of your post you used the getDeclaredConstructors() method and said it was less than ideal; I am not sure what you meant but I suspect it was the hard coded array reference. Anyhow I used the getDeclaredConstructor() method which appears to get non-public constructors also and is basically the same as using the getConstructor() method.
    import java.lang.reflect.*;
    public class Test35 {
        static public void main(String[] args) {
            Test35 t35 = new Test35();
            t35.testIt();
        private class Inner {
            public String toString() {
                return "Hear I am";
        public void testIt() {
            try {
                Constructor con = Inner.class.getDeclaredConstructor(new Class[] {Test35.class});
                Inner in = (Inner)con.newInstance(new Object[] {this});
                System.out.println(in);
            } catch (Exception e) {
                e.printStackTrace();

  • How to override a method in an inner class of the super class

    I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
    The code below is representative of my situation.
    public class ClassA
       ValueChecks vc = null;
       /** Creates a new instance of Main */
       public ClassA()
          System.out.println("ClassA Constructor");
          vc = new ValueChecks();
          vc.checkMaximum();
         // I want this to call the overridden method, but it does not, it seems to call
         // the method in this class. probably because vc belongs to this class
          this.vc.checkMinimum();
          this.myMethod();
       protected void myMethod()
          System.out.println("myMethod(SUPER)");
       protected class ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUPER)");
             return true;
          protected boolean checkMaximum()
             return false;
    }I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
    public class ClassASub extends ClassA
       public ClassAInner cias;
       /** Creates a new instance of Main */
       public ClassASub()
          System.out.println("ClassASub Constructor");
       protected void myMethod()
          System.out.println("myMethod(SUB)");
       protected class ValueChecks extends ClassA.ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUB)");
             return true;
    }The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
    I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.

    vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
    // I want this to call the overridden method, but it does not, it seems to > call
    // the method in this class. probably because vc belongs to this class
    this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
    And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original.

  • Main method not found and how to put event handlers in an inner class

    How would I put all the event handling methods in an inner class and I have another class that just that is just a main function, but when i try to run the project, it says main is not found. Here are the two classes, first one sets up everything and the second one is just main.
    mport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
    private JLabel dateLabel = new JLabel("Date: ");
    private JTextField dateField = new JTextField(20);
    private JPanel datePanel = new JPanel(new FlowLayout());
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel radioPanel = new JPanel();
    JPanel statusPanel = new JPanel();
    JPanel textAreaPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    GridLayout gridLayout1 = new GridLayout();
    FlowLayout flowLayout1 = new FlowLayout();
    GridLayout gridLayout2 = new GridLayout();
    GridLayout gridLayout3 = new GridLayout();
    JRadioButton personalButton = new JRadioButton();
    JRadioButton businessButton = new JRadioButton();
    JLabel status = new JLabel();
    JTextArea entryArea = new JTextArea();
    JButton clearButton = new JButton();
    JButton saveButton = new JButton();
    ButtonGroup entryType = new ButtonGroup();
    public JournalFrame(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void initWidgets(){
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(borderLayout1);
    radioPanel.setLayout(gridLayout1);
    statusPanel.setLayout(flowLayout1);
    textAreaPanel.setLayout(gridLayout2);
    buttonPanel.setLayout(gridLayout3);
    personalButton.setSelected(true);
    personalButton.setText("Personal");
    personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
    businessButton.setText("Business");
    status.setText("");
    entryArea.setText("");
    entryArea.setColumns(10);
    entryArea.setLineWrap(true);
    entryArea.setRows(30);
    entryArea.setWrapStyleWord(true);
    clearButton.setPreferredSize(new Dimension(125, 25));
    clearButton.setText("Clear Journal Entry");
    clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
    saveButton.setText("Save Journal Entry");
    saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
    this.setTitle("Journal");
    gridLayout3.setColumns(1);
    gridLayout3.setRows(0);
    this.getContentPane().add(datePanel, BorderLayout.NORTH);
    this.getContentPane().add(radioPanel, BorderLayout.WEST);
    this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.EAST);
    entryType.add(personalButton);
    entryType.add(businessButton);
    datePanel.add(dateLabel);
    datePanel.add(dateField);
    radioPanel.add(personalButton, null);
    radioPanel.add(businessButton, null);
    textAreaPanel.add(entryArea, null);
    buttonPanel.add(clearButton, null);
    buttonPanel.add(saveButton, null);
    this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
    statusPanel.add(status, null);
    this.pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    private void saveEntry() throws IOException{
    if( personalButton.isSelected())
    String file = "Personal.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    entryArea.getText();
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    else if (businessButton.isSelected())
    String file = "Business.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    void clearButton_actionPerformed(ActionEvent e) {
    dateField.setText("");
    entryArea.setText("");
    status.setText("");
    void saveButton_actionPerformed(ActionEvent e){
    try{
    saveEntry();
    }catch(IOException error){
    status.setText("Error: Could not save journal entry");
    void personalButton_actionPerformed(ActionEvent e) {
    class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.personalButton_actionPerformed(e);
    public class JournalApp {
    public static void main(String args[])
    JournalFrame journal = new JournalFrame();
    journal.setVisible(true);
    }

    Bet you're trying "java JournalFrame" when you need to "java JournalApp".
    Couple pointers toward good code.
    1) Use white space (extra returns) to separate your code into logical "paragraphs" of thought.
    2) Add comments. At a minimum a comment at the beginning should name the file, state its purpose, identify the programmer and date written. A comment at the end should state that you've reached the end. In the middle, any non-obvious code should be commented and closing braces or parens should have a comment stating what they close (if there is non-trivial separation from where they open).
    Here's a sample:
    // JournalFrame.java - this does ???
    // saisoft, 4/18/03
    // constructor
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        radioPanel.setLayout(gridLayout1);
        statusPanel.setLayout(flowLayout1);
        textAreaPanel.setLayout(gridLayout2);
        buttonPanel.setLayout(gridLayout3);
        personalButton.setSelected(true);
        personalButton.setText("Personal");
        personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
        businessButton.setText("Business");
        status.setText("");
        entryArea.setText("");
        entryArea.setColumns(10);
        entryArea.setLineWrap(true);
        entryArea.setRows(30);
        entryArea.setWrapStyleWord(true);
    } // end constructor
    // end JournalFrame.java3) What would you expect to gain from that inner class? It might be more cool, but would it be more clear? I give the latter (clarity) a lot of importance.

  • How to access java method in JSP

    Hi all,
    I need to access java class (abstract portal component) method doContent() in a JSP which is under PORTAL-INF/jsp folder.
    I did
    <%@ page import = "com.mycompany.Aclass" %>
    <%com.mycompany.Aclass a = new com.mycompany.Aclass (); %>
    Aclass is coming as autofill/prepopulated with cntrl+space
    Till this time, it is working. no errors. But when I do
    a.
    a. (a dot) no methods are populating (autofill..cntrl+space) or If I forcebly add method a.doContent(req,res)... at runtime its giving error.
    It's not only with doContent method... Its with any simple methods in that class or any other class.
    (Other than doContent method in the APC java class are prepopulating/autofilling but giving error in runtime)
    Can anyone help me... how to access java method in JSP.
    I already gone through many SDN forum post... and implemented too---but no use I refered below forum thread
    Retrieve values from Java class to JSP
    URGENT! How to call a java class from JSP.
    Calling a java method from jsp file -
    this thread is same as my issue
    Thanks,
    PradeeP

    1st. The classes must be in packages. 2nd, the package that they are in must be under the WEB-INF/classes directory. 3rd Look on google and/or this site for web application deployment

  • How to access a method in webservice catalogued component in BPM Process

    Hi
    Can anyone explain me how to access a method in webservice catalogued component in BPM Process using an imported jsp in bpm process.
    Thanks & Regards
    Ashish

    If Class B only has a reference to an Interface A, and that reference points to a concrete instance of Class A, then of course Class B can still call the method on Interface A. The method for concrete instance Class A is called behind the scenes.
    That's how interfaces work. That's what they're good for.
    Look at the code in the java.sql package for examples. Connection, Statement, ResultSet - all are interfaces. But behind the scenes you're using the concrete implementations provided by your JDBC driver. You don't know or care what those classes are or their package structure. All you do is make calls to the java.sql interface API, and it all works. - MOD

  • OOABAP-How to access the protected methos from a class

    How to access the protected methos from a class..There is a built in class..For tht class i have created a object..
    Built in class name : CL_GUI_TEXTEDIT
    method : LIMIT_TEXT.
    How to access this..help me with code

    hi,
    If inheritance is used properly, it provides a significantly better structure, as common components only
    need to be stored once centrally (in the superclass) and are then automatically available to subclasses.
    Subclasses also profit immediately from changes (although the changes can also render them invalid!).
    Inheritance provides very strong links between the superclass and the subclass. The subclass must
    possess detailed knowledge of the implementation of the superclass, particularly for redefinition, but also in
    order to use inherited components.
    Even if, technically, the superclass does not know its subclasses, the
    subclass often makes additional requirements of the superclass, for example, because a subclass needs
    certain protected components or because implementation details in the superclass need to be changed in
    the subclass in order to redefine methods.
    The basic reason is that the developer of a (super)class cannot
    normally predict all the requirements that subclasses will later need to make of the superclass.
    Inheritance provides an extension of the visibility concept: there are protected components. The visibility of
    these components lies between that of the public components (visible to all users, all subclasses, and the class itself), and private (visible only to the class itself). Protected components are visible to and can be used by all subclasses and the class itself.
    Subclasses cannot access the private components  particularly attributes) of the superclass. Private
    components are genuinely private. This is particularly important if a (super)class needs to make local
    enhancements to handle errors: it can use private components to do this without knowing or invalidating
    subclasses.
    Create your class inse24 and inherit this CL_GUI_TEXTEDIT
    class in yours. You can then access the protected methods.
    Hope this is helpful, <REMOVED BY MODERATOR>
    Edited by: Runal Singh on Feb 8, 2008 1:08 PM
    Edited by: Alvaro Tejada Galindo on Feb 19, 2008 2:19 PM

  • Access DataControls methods in a java class

    Hi All,
    Jdeveloper Version 11.1.5
    I have created DataControls for SessionFacade web service.
    Inside the datacontrol there is a method getAllDepartments() which have a Return type which includes DaertmentId,DepartmentName,....
    I want to know how can i access this method inside a Java Class and create a list of only departmentId.

    You would need to add the method in the data control as a method action in your pageDef.
    After that, you could access the method as mentioned above.
    Thanks,
    Navaneeth

  • How to access the text symbols of a class

    Hi Experts,
    Can anyone pl. tell me how to access the text symbols of a class.
    Thanks,
    Uday.

    Hi,
    Please check
    http://help.sap.com/saphelp_nw04s/helpdata/en/43/1f6442a3d9e72ce10000000a1550b0/frameset.htm

  • Accessing method in an inner class

    I have a class, which has an Inner Class, which is an extension of AbstractTableModel. The extended TableModel class has a new method, so it looks something like this;
    public class TheOuterClass
        JTable aTable
        TableModel theTableModel
        public initTable
             theTableModel = new MyTableModel();
         public TableModel getModel()
             return theTableModel;
         private class MyTableModel extends AbstractTableModel
                public void myTableModelMethod()
    }So, the idea here is that I have a class that has a table referenced by 'aTable', which uses MyTableModel as the class for it's table model. I have only implemented the basics here. The class also has a method called getModel(), so from a reference to 'TheOuterClass', I can access the table model.
    Now, say I have a reference to TheOuterClass called toc, and I want to access my new method in the table model;
    toc.getModel().myTableModelMethod()The above won't work, because getModel() returns a type of TableModel.
    My question then is how do I cast this to the correct type, so I can access the method 'myTableMethod()'?
    Is for example, the following a legal possibility, because I cannot seem to make it work;
    (toc.getModel().getClass())(toc.getModel()).myTableMethod();The quick fix, I guess is to correct getModel in TheOuterClass, so it returns the correct type, but I am hoping to not do this. (This is part of a larger piece of code obviously, and TheOuterClass is in reality a bean, and I don't wnat to disturb anymore than I have to).
    Any suggestions / ideas would be gratefully appreciated

    You are of course both correct, the class is private, should have spotted that! Doh. Also correct in that this is 'not the most elegant design', but you know the way it is you have to work with what you are given.
    So, I changed the class to public....
    What I had hoped is that the following would work
    ((toc.getModel().getClass())(toc.getModel())).myTableMethod()get a reference to the table model
    (toc.getModel())cast it to the correct type (not sure if this is a valid way to cast??)
    ((toc.getModel().getClass())(toc.getModel()))then call the method.
    This does not compile, it complains about a missing ')', and I'm sure they are all there. My question here then is, Is this a valid way to cast, now that the inner class is public?
    As to why I want to do this, then some explanation is required;
    The table model holds a Vector with all the data in it, some which is not actually in the table (it was originally written this way). My additional method myTableMethod() is intended to help access the data that is not shown in the table.
    Coming back to kajbj's point of creating an interface, I presume what is being suggested is that I create a public interface with the myTableMethod() in it, and make myTableModel implement this interface. Since the interface is public, then I can cast to that. Is this what you meant?
    Thanks for your help so far

  • How to access private attribute of a class from its Friend Class

    Hi Experts ,
    I am coding in Method (DO_SAVE) of class /BOBF/CL_TRA_TRANSACTION_MGR.
    I need to access private variable ( MO_BOPF) of class /BOBF/CL_TRA_SERVICE_MGR ( Friend of /BOBF/CL_TRA_TRANSACTION_MGR ).
    Please help me to understand how can i access private attribute of one class from its friend class.
    Regards- Abhishek

    Hi Reny,
    You should be able to access by creating object of friend class.
    Sample:
    data lo_frnd     TYPE REF TO  /BOBF/CL_TRA_SERVICE_MGR.
    data lo_compl  type REF TO /BOBF/IF_TRA_TRANS_MGR_COMPL.
       create OBJECT lo_frnd
         exporting
                   iv_bo_key = '111'
                   IO_COMPL_TRANSACTION_MANAGER = lo_compl.
    "access the private object of friend class
       clear lo_frnd->MO_BOPF.
    Note: need to provide iv_bo_key & IO_COMPL_TRANSACTION_MANAGER while creating object.
    Hope this helps you.
    Regards,
    Rama

  • How to access a method of a class which just known class name as String

    Hi,
    Now I have several class and I want to access the method of these class. But what I have is a String which contain the complete name of the class.
    For example, I have two class name class1and class2, there are method getValue in each class. Now I have a String containing one class name of these two class. I want to access the method and get the return value.
    How could I do?
    With Class.forName().newInstance I can get a Object. but it doesn't help to access and execute the method I want .
    Could anybody help me?
    Thanks

    Or, if Class1 and Class2 have a common parent class or interface (and they should if you're handling them the same way in the same codepath)...Class c = Class.forName("ClassName");
    Object o = c.newInstance(); // assumes there's a public no-arg constructor
    ParentClassOrInterface pcoi = (ParentClassOrInterface)o;
    Something result = pcoi.someMethod(); Or, if you're on 5.0, I think generics let you do it this way: Class<ParentClassOrInterface> c = Class.forName("ClassName");
    // or maybe
    Class<C extends ParentClassOrInterface> c = Class.forName("ClassName");
    ParentClassOrInterface pcoi = c.newInstance();
    Something result = pcoi.someMethod();

  • Accessing private method of a class from report

    Hello All,
    I would have to access a private method of a class from a report.
    Is it possible to access private mehod otherthan from its own class and friend classes.
    Please guide on this. If is possible, to access please give some sample code.
    Thanks & Regards,
    Vishnu Priya

    Hi,
    By using the friend concept you can access private attribute or method in outside class.
    Try the following code,
    CLASS C1 DEFINITION DEFERRED.
    CLASS C2 DEFINITION CREATE PRIVATE FRIENDS C1 .
    PRIVATE SECTION.
    DATA : NUM TYPE I VALUE 5.
    METHODS : M2.
    ENDCLASS.
    CLASS C2 IMPLEMENTATION.
    METHOD M2.
    WRITE:/5 'I am method m2 in C2'.
    ENDMETHOD.
    ENDCLASS .
    class c1 definition.
    public section .
    methods : m1.
    endclass.
    class c1 implementation.
    method m1.
    DATA : OREF2 TYPE REF TO C2.
    CREATE OBJECT OREF2.
    WRITE:/5 OREF2->NUM.
    CALL METHOD OREF2->M2.
    ENDMETHOD.
    endclass.
    START-OF-SELECTION.
    DATA : OREF1 TYPE REF TO C1.
    CREATE OBJECT OREF1.
    CALL METHOD OREF1->M1.
    Regards,
    Jeyakumar.A
    Edited by: Jeyakumar Aasai on Apr 14, 2011 11:51 AM

  • How to Access Protected Method of a Class

    Hi,
         I need to access a Protected method (ADOPT_LAYOUT) of class CL_REIS_VIEW_DEFAULT.
    If i try to call that method by using class Instance it is giving error as no access to protected class. Is there any other way to access it..

    Hi,
        You can create a sub-class of this class CL_REIS_VIEW_DEFAULT, add a new method which is in public section and call the method ADOPT_LAYOUT of the super-class in the new method. Now you can create an instance of the sub-class and call the new sub-class method.
    REPORT  ZCD_TEST.
    class sub_class definition inheriting from CL_REIS_VIEW_DEFAULT.
    public section.
      methods: meth1 changing cs_layout type LVC_S_LAYO.
    endclass.
    class sub_class implementation.
    method meth1.
      call method ADOPT_LAYOUT changing CS_LAYOUT = cs_layout.
    endmethod.
    endclass.
    data: cref type ref to sub_class.
    data: v_layout type LVC_S_LAYO.
    start-of-selection.
    create object cref.
    call method cref->meth1 changing cs_layout = v_layout.

Maybe you are looking for