我有一个类,其构造函数被定义为内部,这意味着我无法实例化它.虽然这可能有意义,但我仍然希望这样做一次用于调试和研究目的.
用反射可以做到吗?我知道我可以访问私人/内部成员,但我可以调用内部构造函数吗?
或者,由于构造函数没有什么重要的,我可以使用反射来说"看,只需给我一个类的实例而不调用构造函数,我会手动完成它的工作"?
性能和"稳定性"在这里不是问题,因为它不是生产代码.
编辑:正如澄清:遗憾的是,我不控制其他程序集并且没有它的源代码,我只是试图理解它是如何工作的,因为它的文档旁边是不存在的,但我应该与它.
基于其缓慢的声誉,我总是避免使用Java反射.我在当前项目的设计中达到了一个重点,能够使用它会使我的代码更具可读性和优雅性,所以我决定试一试.
我对这种差异感到惊讶,有时候我注意到运行时间差了近100倍.即使在这个简单的例子中它只是实例化一个空类,它也令人难以置信.
class B {
}
public class Test {
public static long timeDiff(long old) {
return System.currentTimeMillis() - old;
}
public static void main(String args[]) throws Exception {
long numTrials = (long) Math.pow(10, 7);
long millis;
millis = System.currentTimeMillis();
for (int i=0; i<numTrials; i++) {
new B();
}
System.out.println("Normal instaniation took: "
+ timeDiff(millis) + "ms");
millis = System.currentTimeMillis();
Class<B> c = B.class;
for (int i=0; i<numTrials; i++) {
c.newInstance();
}
System.out.println("Reflecting instantiation took:"
+ timeDiff(millis) + "ms");
} …Run Code Online (Sandbox Code Playgroud) 我在我的测试框架中有一个方法,它创建一个类的实例,具体取决于传入的参数:
public void test(Object... constructorArgs) throws Exception {
Constructor<T> con;
if (constructorArgs.length > 0) {
Class<?>[] parameterTypes = new Class<?>[constructorArgs.length];
for (int i = 0; i < constructorArgs.length; i++) {
parameterTypes[i] = constructorArgs[i].getClass();
}
con = clazz.getConstructor(parameterTypes);
} else {
con = clazz.getConstructor();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,如果构造函数具有基本类型,则不起作用,如下所示:
public Range(String name, int lowerBound, int upperBound) { ... }
.test("a", 1, 3);
Run Code Online (Sandbox Code Playgroud)
结果是:
java.lang.NoSuchMethodException: Range.<init>(java.lang.String, java.lang.Integer, java.lang.Integer)
Run Code Online (Sandbox Code Playgroud)
原始int是自动装入对象版本的,但是如何让它们返回以调用构造函数?
我正在尝试为Enumerable类型的Where方法检索MethodInfo:
typeof (Enumerable).GetMethod("Where", new Type[] {
typeof(IEnumerable<>),
typeof(Func<,>)
})
Run Code Online (Sandbox Code Playgroud)
但得到null.我究竟做错了什么?
我已经向Google报告了问题78084,因为该setMobileDataEnabled()方法不再可以通过反射调用.它可以通过反射从Android 2.1(API 7)到Android 4.4(API 19)进行调用,但是从Android L及更高版本开始,即使使用root,该setMobileDataEnabled()方法也不可调用.
官方回应是问题是"已关闭",状态设置为"WorkingAsIntended".谷歌的简单解释是:
私有API是私有的,因为它们不稳定,可能会在没有通知的情况下消失.
是的,谷歌,我们意识到使用反射调用隐藏方法的风险 - 甚至在Android出现之前 - 但是你需要提供一个更加可靠的答案,如果有的话,可以实现相同的结果setMobileDataEnabled().(如果您对Google的决定不满意,请登录问题78084,并尽可能多地将其加注,以便让Google知道他们的错误.)
所以,我的问题是:在Android设备上以编程方式启用或禁用移动网络功能时,我们是否处于死胡同?谷歌的这种严厉的方法在某种程度上并不适合我.如果您有Android 5.0(Lollipop)及其他方法的解决方法,我很乐意听到您在此主题中的回答/讨论.
我使用下面的代码来查看该setMobileDataEnabled()方法是否可用:
final Class<?> conmanClass = Class.forName(context.getSystemService(Context.CONNECTIVITY_SERVICE).getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(context.getSystemService(Context.CONNECTIVITY_SERVICE));
final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method[] methods = iConnectivityManagerClass.getDeclaredMethods();
for (final Method method : methods) {
if (method.toGenericString().contains("set")) {
Log.i("TESTING", "Method: " + method.getName());
}
}
Run Code Online (Sandbox Code Playgroud)
但事实并非如此.
更新:目前,如果设备已植根,则可以切换移动网络.但是,对于非根设备,它仍然是一个调查过程,因为没有通用的方法来切换移动网络.
我需要在Java中进行一些反射方法调用.这些调用将包含具有基本类型(int,double等)的参数的方法.反向查找方法时指定此类型的方法是int.class,double.class等.
挑战在于我接受来自外部源的输入,该源将动态指定类型.因此,我还需要动态地提出这些类引用.想象一下分隔文件的方法名列表以及参数类型列表:
doSomething int double
doSomethingElse java.lang.String boolean
Run Code Online (Sandbox Code Playgroud)
如果输入类似java.lang.String,我知道我可以使用Class.forName("java.lang.String")该类实例.有没有办法使用该方法或其他方法来获取原始类型Classes?
编辑:
感谢所有受访者.很明显,没有内置的方法来干净地做我想要的事情,所以我将决定重用ClassUtilsSpring框架中的类.它似乎包含Class.forName()的替代品,可以满足我的要求.
使用Java类上的反射来访问所有字段,方法等:
这些元素是否有标准化顺序(在某些标准中指定)?
当然,我可以凭经验检查,但我需要知道它是否总是一样的.
编辑:
我等待的问题:我需要的订单;)
长话短说:我有JAXB注释类,并且不希望在视觉上代表这些类.虽然XML属性的顺序既不与XML标准相关,也不与JAXB相关,但我希望对可视表示具有特定顺序的XML属性.
例如:开始结束.这伤害了一个人的直觉.
使用反射来获取MethodInfo,我想测试返回的类型是否为typeof System.Void.
测试它是否是System.Int32正常工作
myMethodInfo.ReturnType == typeof(System.Int32)
Run Code Online (Sandbox Code Playgroud)
但
myMethodInfo.ReturnType == typeof(System.Void)
Run Code Online (Sandbox Code Playgroud)
不编译?目前我正在测试名称的字符串表示是否为"System.Void",这看起来非常错误.
如何获得实现特定开放泛型类型的所有类型?
例如:
public interface IUserRepository : IRepository<User>
Run Code Online (Sandbox Code Playgroud)
找到所有实现的类型IRepository<>.
public static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(Type openGenericType, Assembly assembly)
{
...
}
Run Code Online (Sandbox Code Playgroud) 我最近不得不将这个怪物检入生产代码来操作WPF类中的私有字段:( tl; dr我如何避免这样做?)
private static class MemoryPressurePatcher
{
private static Timer gcResetTimer;
private static Stopwatch collectionTimer;
private static Stopwatch allocationTimer;
private static object lockObject;
public static void Patch()
{
Type memoryPressureType = typeof(Duration).Assembly.GetType("MS.Internal.MemoryPressure");
if (memoryPressureType != null)
{
collectionTimer = memoryPressureType.GetField("_collectionTimer", BindingFlags.Static | BindingFlags.NonPublic)?.GetValue(null) as Stopwatch;
allocationTimer = memoryPressureType.GetField("_allocationTimer", BindingFlags.Static | BindingFlags.NonPublic)?.GetValue(null) as Stopwatch;
lockObject = memoryPressureType.GetField("lockObj", BindingFlags.Static | BindingFlags.NonPublic)?.GetValue(null);
if (collectionTimer != null && allocationTimer != null && lockObject != null)
{
gcResetTimer = new Timer(ResetTimer);
gcResetTimer.Change(TimeSpan.Zero, …Run Code Online (Sandbox Code Playgroud) reflection ×10
c# ×5
java ×4
.net ×2
android ×1
generics ×1
methodinfo ×1
performance ×1
primitive ×1
types ×1
wpf ×1