给定一个Java类,我希望能够列出在所有祖先中公开的所有属性,并public以相同的方式递归遍历所有公开的属性(即或使用getter/setter).
用一个简单的例子更容易解释:
public class BaseClass1 {
private int intProperty; // has getter and setter (not shown)
}
public class SubClass1 extends BaseClass1 {
private int privateSoNotListed;
public SubClass2 subClass2Property;
}
public class BaseClass2 {
public String stringProperty;
}
public class SubClass2 extends BaseClass2 {
private long longProperty; // has getter and setter (not shown)
}
Run Code Online (Sandbox Code Playgroud)
鉴于SubClass1上面的输入,输出会是这样的:
intProperty - int [from BaseClass1]
subClass2Property.stringProperty - String [from BaseClass2]
subClass2Property.longProperty - long [from SubClass2]
Run Code Online (Sandbox Code Playgroud)
应该可以使用一些巧妙的反射来写这样的东西,但我宁愿不重新发明轮子 - 是否有现成的工具可以做到这一点(也许是一个Eclipse插件?)
编辑: Eclipse的类型层次结构可以很好地显示单个类的属性 …
假设我有一个班级:
public final class Foo
以及Class clz引用该类的反映参考.
我怎么知道(使用clz)那Foo是final什么?
当我声明以下简单类时:
class Class1<T>
{
protected virtual T Prop1 { get; set; }
protected virtual string Prop2 { get; set; }
}
class Class2 : Class1<string>
{
protected override string Prop1 { get; set; }
protected override string Prop2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在我使用Reflection来获取Class2的属性,如下所示:
var hProperties = typeof(Class2).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
Run Code Online (Sandbox Code Playgroud)
然后Prop2将列出一次,而Prop1将列出两次!这种行为对我来说似乎很奇怪.Prop1和Prop2不应该被视为相同吗?
如何在hProperties中只使用Prop1一次?我不想使用BindingFlags.DeclaredOnly,因为我还想获得未被覆盖的Class1的其他受保护属性.
如果我有这样的代码:
public class Program
{
public static void Main()
{
string bar = "";
int foo = 24;
}
}
Run Code Online (Sandbox Code Playgroud)
我可以Main使用以下方法获取声明的局部变量:
var flag = BindingFlags.Static | BindingFlags.Public;
var fields = typeof(Program).GetMethod("Main", flags).GetMethodBody().LocalVariables;
Run Code Online (Sandbox Code Playgroud)
这将返回一个IList<LocalVariableInfo>与LocalVariableInfo只有三个属性:IsPinned,LocalIndex和LocalType.所以没有Name财产存在.
我想知道的是你可以看到生成的变量名称IL code:
.method public hidebysig static void Main() cil managed
{
.entrypoint
// Code size 11 (0xb)
.maxstack 1
.locals init ([0] string bar,
[1] int32 foo)
IL_0000: nop
IL_0001: ldstr …Run Code Online (Sandbox Code Playgroud) 在Java文档中,它提到使用f.setAccessible(true)方法我们可以违反封装的原则.
但是如果我正在编写任何具有完全安全性的类,例如使用私有变量,我怎么能防止它被反射访问?
例如,我有一个具有完整安全实例变量的类:
public final class Immutable {
private final int someVal;
public Immutable(int someVal) {
this.someVal = someVal;
}
public int getVal() {
return someVal;
}
}
Run Code Online (Sandbox Code Playgroud)
但我可以使用这样的反射修改该实例变量:
public class Tester {
public static void main(String[] args)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
Immutable i = new Immutable(10);
// output 10
System.out.println(i.getVal());
Field f = i.getClass().getDeclaredField("someVal");
f.setAccessible(true);
f.set(i, 11);
// output is 11 which implies some value modified
System.out.println(i.getVal());
}
}
Run Code Online (Sandbox Code Playgroud)
在我的代码中,如何防止使用反射更改不可变类?
SO上有两个类似的问题:
但是,很有趣,他们都没有给出完全正确的答案.
我和其他问题的作者真正想要的是,某些库中的一些方法只会告诉两个对象是否相等:
boolean deepEquals(Object obj1, Object obj2)
即没有抛出任何异常等等.
apache这EqualsBuilder不是方法,因为它没有深刻的比较.
Unitils似乎也是不好的决定,因为它的方法不回归true或false; 如果比较失败,它只会引发异常.当然,它可以像这样使用:
Difference difference = ReflectionComparatorFactory.createRefectionComparator(new ReflectionComparatorMode[]{ReflectionComparatorMode.LENIENT_ORDER, ReflectionComparatorMode.IGNORE_DEFAULTS}).getDifference(oldObject, newObject);
但它似乎非常难看,并且unitils库完全似乎太难以进行必要的比较.
此外,很清楚如何deepEquals通过self 创建这样的,但是不太可能没有包含已经实现的方法的常用库.有任何想法吗?
在clojure中,如何列出命名空间的功能的答案?如果我有一个命名空间,它是有用的,特别是(ns-imports 'my-package)可以告诉我已经导入的Java代码.我可以找到命名空间列表(all-ns).是否有类似的方法来查找所有可用java包的列表,并预览尚未导入的java类?
我正在通过从Leiningen很多JAR和.class文件的:resource-paths和:java-source-paths分别.但由于我是Java代码库的新手,我实际上并不知道为了导入它们而定义了哪些包.我可以用find,xargs和grep做一些事情,但以编程方式提供这些信息会很不错.此外,在将来,我希望能够在Clojure中对Java代码库进行"反思",例如,注意何时定义了新类.
在LISP的世界里,有一个叫功能`做外部的符号,我用Google搜索的是,调高这个从2007年的讨论,似乎事情已经解决了Clojure的本身,但它是关于Java的Clojure的看法不太清楚.
我在应用程序中使用传统MainMenu控件(带MenuItems)控件,并希望实现放大和缩小菜单项(使用Control+ +和Control+ -键盘快捷键).(注意我正在使用MainMenu而不是MenuStrip).MenuItem确实有一个Shortcut类型的属性,Shortcut但没有CtrlPlus选项.
我决定看一下在Shortcutreferencesource中是如何实现的,看起来每个枚举值的方式只是几个Keys枚举值的组合(例如CtrlA只是Keys.Control + Keys.A).所以我尝试创建一个自定义的快捷方式值,该值应该等于Control + Plus:
const Shortcut CONTROL_PLUS = (Shortcut)(Keys.Control | Keys.Oemplus);
zoomInMenuItem.Shortcut = CONTROL_PLUS;
Run Code Online (Sandbox Code Playgroud)
但是,这会InvalidEnumArgumentException在我尝试分配Shortcut属性时抛出.
所以我决定使用反射,修改(不公开)MenuItemData的shortcut属性,然后调用(非公共)UpdateMenuItem方法.这实际上有效(具有Control+Oemplus在菜单项中显示的副作用):
const Shortcut CONTROL_PLUS = (Shortcut)(Keys.Control | Keys.Oemplus);
var dataField = typeof(MenuItem).GetField("data", BindingFlags.NonPublic | BindingFlags.Instance);
var updateMenuItemMethod = …Run Code Online (Sandbox Code Playgroud) 我正在开发一个代码生成器,它在运行时从类中获取数据.该发生器仅适用于Kotlin.目前,我遇到了问题,因为我不知道如何检查该字段是否可以为空.
所以主要的问题是如何通过反射实现这种检查?
我从加载的程序集中读取类型,例如:
var someType = loadedAssemblies
.Where(a => a != null && a.FullName.StartsWith("MY."))
.SelectMany(a => a.GetTypes())
.Distinct()
.ToArray()[0];
Run Code Online (Sandbox Code Playgroud)
如果counstructor有参数,我可以读它们:
ParameterInfo[] parameters = classType.GetConstructors()[0].GetParameters();
Run Code Online (Sandbox Code Playgroud)
我想用默认参数值调用构造函数,或者如果参数是枚举,则使用第一个枚举值.如果只有一个参数并且它是枚举,则它的工作方式如下:
object curObject = Activator.CreateInstance(classType, new object[] { parameters[0].ParameterType.GetEnumValues().GetValue(0) });
Run Code Online (Sandbox Code Playgroud)
如果有更多参数,我该怎么做?我需要创建对象来读取属性:
var propertyInfo = someType.GetProperty("EntityType");
string entityType = propertyInfo.GetValue(curObject, null).ToString();
Run Code Online (Sandbox Code Playgroud)