如何在无源码权限下获取对象所有可用的public方法名称?
无源码、禁用额外自定义反射逻辑下打印对象公开方法的方案
以下方案均使用对应编程语言的原生内置API,无需额外编写自定义反射逻辑、无需查看或修改底层源码即可直接运行:
Python 方案
直接调用内置dir()函数获取对象所有属性方法,过滤后得到公开方法:
# 目标对象实例 target = myObject[1] # 过滤公开可调用方法,排除魔术方法、私有属性 public_methods = [ attr for attr in dir(target) if not attr.startswith('_') and callable(getattr(target, attr)) ] # 格式化打印 for method in public_methods: print(f".{method}()")
Java 方案
使用JDK核心类java.beans.Introspector直接提取类的get/set方法,完全匹配你需要的 getter/setter 输出格式:
import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; // 目标对象实例 Object target = myObject[1]; BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass(), Object.class); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : propertyDescriptors) { // 打印get方法 System.out.printf(".get%s()%n", pd.getName()); // 打印存在的set方法 if (pd.getWriteMethod() != null) { System.out.printf(".set%s(newValue)%n", pd.getName()); } }
JavaScript/TypeScript 方案
遍历实例原型链提取所有公开方法:
function getPublicMethods(obj) { const methodSet = new Set() let currentProto = Object.getPrototypeOf(obj) // 遍历到顶层Object原型停止 while (currentProto && currentProto !== Object.prototype) { Object.getOwnPropertyNames(currentProto).forEach(prop => { if (typeof obj[prop] === 'function' && prop !== 'constructor') { methodSet.add(prop) } }) currentProto = Object.getPrototypeOf(currentProto) } return Array.from(methodSet) } // 调用并格式化输出 getPublicMethods(myObject[1]).forEach(method => console.log(`.${method}()`))
C# 方案
使用.NET 内置的类型元数据API提取公开方法:
var target = myObject[1]; var publicMethods = target.GetType().GetMethods( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly ); foreach (var method in publicMethods) { // 过滤属性自动生成的特殊命名方法,不需要可删除该判断 if (!method.IsSpecialName) { Console.WriteLine($".{method.Name}()"); } }
补充备选方案:如果运行环境完全禁用元数据访问能力,可根据行业通用命名规则反向推导:你已知的get类方法(如
.getDimUom())大概率对应相同命名前缀的set类方法(如.setDimUom(newValue)),可大幅降低试错成本。
内容的提问来源于stack exchange,提问作者Edward
相关产品推荐
相关产品推荐

