简体   繁体   中英

How to refer a private method for a Supplier or Consumer in java

I want to reuse a piece of code written in Private method of another class A. Like

class A
{
  private String method(String data){
return "abcd";
}
}

List myList= getListFromSomeSource();
myList.stream()
.map(A::method)
.collect()....etc

The only way to access a private method of a class, if the class implementation does not provide such an option and if that implementation cannot be modified, is via reflection.

Assuming that the method function of class A has a String return type, a simple way to do so is

public static String invokeMethod(A object, String data) throws Exception {
  Method method = A.class.getDeclaredMethod(“method”, String.class);
  method.setAccessible(true);
  return (String) method.invoke(object, data);
}

Since the Class A method in question is not static, an object reference would need to be used to access it, with or without reflection, eg

A object = new A(); // Create object of type A
String data = “...”; // Specify data input
String result = invokeMethod(object, data); // Call method

If such an object of type A cannot be created, or if the caller does not want to pass to invokeMethod a reference to such an object, the only other option left is actually rewriting the method function, outside Class A .

you can create a new object of class A ,and then,you can use this private method Like A a = new A(); a.method();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM