反射不是通过get取值的,是通过该对象的信息,比如说名称、内存地址等来访问类,方法,属性等,可以获取任意对象的信息,但不能获得私有属性(private String s=“sd”;)的值,切记
推荐《JAVA核心技术》这本书会对你有帮助的
Class<> obj=ClassforName(refgetClass()getName());
Object object = objnewInstance();
Method method=objgetMethod("getLength");
你这样拿到的是你newInstance新构建的对象,又不是你之前设定了值的对象,域当然会是0
应该是这样:methodinvoke(ref)
class
Program
{
static
void
Main(string[]
args)
{
string
path
=
@"D:\OpenSSL";
//
ConsoleWriteLine(isDir(path));
//ConsoleRead();
Man
man
=
new
Man();
Type
type
=
manGetType();
PropertyInfo[]
infos
=
typeGetProperties();
foreach
(PropertyInfo
info
in
infos)
{
ConsoleWriteLine(infoDeclaringTypeFullName
+
"
,
"
+
infoName);
}
ConsoleRead();
}
}
public
class
Person
{
public
string
name
{
get;
set;
}
public
string
password
{
get;
set;
}
}
public
class
Man
:
Person
{
public
string
height
{
get;
set;
}
public
string
weight
{
get;
set;
}
}
比较笨的办法。
肯定有更优解决方案。
你是想通过反射获得该类所有属性值或是给所有属性赋值吧。用getMethods获取所有的getter和setter方法,再取值或赋值。但不要用getDeclaredMethods,因为getMethods反映此 Class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共 member 方法;而getDeclaredMethods反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。
这也许是框架注入属性值都采用setter注入的原因吧。
以上就是关于java反射取对象属性值 不是通过get方法取值全部的内容,包括:java反射取对象属性值 不是通过get方法取值、怎样通过反射获得一个类的属性值或者方法返回值、C# 反射获取属性的时候如何只获取该类的属性,我不想取得父类的属性。等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)