java私有方法_如何调用私有方法
當不涉及到用戶隱私的時候,我們調用私有方法一般都沒有什么問題。
在我們調用私有方法之前,我們必須要先知道你想調用的對象有哪些私有方法,和需要參數的那些方法的參數類型,和返回值的類型是多少。
查看私有方法名,參數類型和返回值類型
- (void)scanMethodsTwo:(Class)class {
unsigned int outCount = 0; // unsigned int :是無符號基本整型,沒有負數
Method *methods = class_copyMethodList(class, &outCount); // 獲取類的方法列表
for (int i = 0; i < outCount; i++) {
Method method = methods[i];
// 獲取方法名
SEL sel = method_getName(methods[i]);
NSLog(@"方法名==== %@", NSStringFromSelector(sel));
// 獲取參數
char argInfo[512] = {};
unsigned int argCount = method_getNumberOfArguments(method);
for (int j = 0; j < argCount; j++) {
// 參數類型
method_getArgumentType(method, j, argInfo, 512);
NSLog(@"參數類型=== %s", argInfo);
memset(argInfo, '\0', strlen(argInfo));
}
// 獲取方法返回值類型
char retType[512] = {};
method_getReturnType(method, retType, 512);
NSLog(@"返回值類型=== %s", retType);
}
free(methods);
}
調用無參數方法
當知道方法名過后,我們調用沒有參數的私有方法,有兩種:
方法一:使用performSelector來調用
[button performSelector:@selector(updateConstraints)];
方法二:也可以使用objc_msgSend來調用,但是是有這個必須要導入#import ,#import 這兩個頭文件。
((void(*)(id,SEL))objc_msgSend)(button, @selector(updateConstraints));
如果要使用下面這種寫法,必須要在項目配置文件 -> Build Settings -> Enable Strict Checking of objc_msgSend Calls 這個字段設置為 NO, 默認為YES.
objc_msgSend(button, @selector(updateConstraints));
調用有參數方法
要使用objc_msgSend來調用,并傳遞參數
((void(*)(id,SEL, CGRect))objc_msgSend)(button, @selector(setFrame:), CGRectMake(200, 100, 50, 50));
objc_msgSend(button, @selector(setFrame:), CGRectMake(200, 100, 50, 50));
總結
以上是生活随笔為你收集整理的java私有方法_如何调用私有方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用Python计算身份证校验码
- 下一篇: C++中 #if #endif 和#if