如何在不同的包中调用类的私有方法

Bha*_*shu 0 java

BookView.class有一个私有方法,如下所示

  public class BookView{
    private boolean importBook(String epubBookPath){
    //The function that adds books to database.
    }
  }
Run Code Online (Sandbox Code Playgroud)

我试图从另一个包中调用此函数.我的代码是

    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        dismissDialog(progress_bar_type);

        /*Now we add the book information to the sqlite file.*/
        TextView textView=(TextView)findViewById(R.id.textView1);
        String filename = textView.getText().toString();
        String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        String epubBookPath = baseDir+filename;
        Log.i("epubBookPath:",epubBookPath); //No errors till here!

        try {
            Method m=BookView.class.getDeclaredMethod("importBook");
            m.setAccessible(true);//Abracadabra 
            //I need help from here! How do i pass the epubBookPath to the private importBook method.
        } catch (NoSuchMethodException e) {

            e.printStackTrace();
        }
        Intent in = new Intent(getApplicationContext(),
                CallEPubUIActivity.class);        
        startActivity(in);
    }
Run Code Online (Sandbox Code Playgroud)

编辑:

我在jar文件中找到了另一个公共方法,它正在进行上述工作.

  public void jsImportBook(String epubBookPath) {
     if (!BookView.this.importBook(epubBookPath))
     return;
   BookView.this.createBookshelf();
  }
Run Code Online (Sandbox Code Playgroud)

Ang*_*chs 11

如果你想这样做,你应该制作它public或制作一个public包装方法.

如果那不是可能的,你可以以你的方式围绕它,但多数民众赞成丑陋和坏的,你应该有真的很好的理由这样做.

public boolean importBook(String epubBookPath){
    //The function that adds books to database.
}
Run Code Online (Sandbox Code Playgroud)

要么

public boolean importBookPublic(String epubBookPath){
    return importBook(epubBookPath);
}
private boolean importBook(String epubBookPath){
    //The function that adds books to database.
}
Run Code Online (Sandbox Code Playgroud)

另请注意,如果您无法直接在第三方库中访问该方法,那么它很可能是以这种方式进行的.看一下方法的调用层次结构,private看看你是否找到了一个public方法来调用一个方法,并且private你也可以做你需要的方法.

库通常以某种方式进行设计,即public方法进行一些检查(所有参数给定,经过验证等),然后将调用传递给private方法来完成实际工作.你几乎从不想解决这个过程.

  • 如果可能的话+1,总是使用包装而不是反射. (2认同)

Sot*_*lis 8

使用反射,您需要一个BookView实例来调用该方法(除非它是一个静态方法).

BookView yourInstance = new BookView();
Method m = BookView.class.getDeclaredMethod("importBook");
m.setAccessible(true);//Abracadabra 
Boolean result = (Boolean) m.invoke(yourInstance, "A Path"); // pass your epubBookPath parameter (in this example it is "A Path"
Run Code Online (Sandbox Code Playgroud)

你正在寻找的方法是 Method#invoke(Object, Object...)