我的代码如下所示:
class MyObject {
MyField f = new MyField();
}
class MyField {
public void greatMethod();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法greatMethod()在类的对象上调用using反射MyObject?
我尝试了以下方法:
Field f = myObject.getClass().getDeclaredField("f");
Method myMethod = f.getDeclaringClass().getDeclaredMethod("greatMethod", new Class[]{});
myMethod.invoke(f);
Run Code Online (Sandbox Code Playgroud)
但是它试图greatMethod()直接调用我的myObject,而不是调用其中的字段f.有没有办法实现这一点,而无需修改MyObject类(因此它将实现一个在f上调用适当方法的方法).
我在调用反射值的.FieldByName方法时遇到以下错误,确切的错误是: -
panic: reflect: call of reflect.Value.FieldByName on ptr Value
Run Code Online (Sandbox Code Playgroud)
而代码是: -
s := reflect.ValueOf(&value).Elem() (value is a struct)
metric := s.FieldByName(subval.Metric).Interface() (subval.Metric is a string)
Run Code Online (Sandbox Code Playgroud)
我知道这并不多,但这是我能得到的所有信息.
这是Go Playground代码的链接:http://play.golang.org/p/E038cPOoGp
在Scala中,我有一个注释和带有注释的基本特征,但扩展该类不会继承注释:
scala> import scala.annotation.StaticAnnotation
import scala.annotation.StaticAnnotation
scala> case class AnnotationClass() extends StaticAnnotation
defined class AnnotationClass
scala> @AnnotationClass trait BaseTrait
defined trait BaseTrait
scala> class InheritingClass extends BaseTrait
defined class InheritingClass
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> typeOf[BaseTrait].typeSymbol.asClass.annotations.size
res1: Int = 1
scala> typeOf[InheritingClass].typeSymbol.asClass.annotations.size
res0: Int = 0
Run Code Online (Sandbox Code Playgroud)
有没有办法让子类继承父级的注释?
假设我有一个带有以下DbSet的DbContext
class Amimals : DbContext
{
public DbSet<Dog> Dogs { get; set; }
public DbSet<Cat> Cats { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在每个EntityTypeConfiguration内部,我为每个DbSet定义表
class DogConfig : EntityTypeConfiguration
{
public DogConfig()
{
this.ToTable("DOG_TABLE");
...
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我有表名和DbContext,我怎样才能获取并使用正确的DbSet?
void foo()
{
string tableName = this.GetTableName();
using(Animals context = new Animals())
{
/* Made up solution */
DbSet animalContext = context.Where(c => c.TableName == tableName);
...
/* Do something with DbSet */
...
}
}
Run Code Online (Sandbox Code Playgroud) 我正在编写一个程序,根据许多复杂的规则验证复杂的数据结构.它输入数据并输出指示数据问题的消息列表.
按照以下思路思考:
import Control.Monad (when)
import Control.Monad.Writer (Writer, tell)
data Name = FullName String String | NickName String
data Person = Person { name :: Name, age :: Maybe Int }
data Severity = E | W | C -- error/warning/comment
data Message = Message { severity :: Severity, code :: Int, title :: String }
type Validator = Writer [Message]
report :: Severity -> Int -> String -> Validator ()
report s c d = tell [Message s c …Run Code Online (Sandbox Code Playgroud) 2015年8月28日更新: 这将在Swift 2中解决
2015年10月23日更新:使用Swift 2泛型,您仍然无法获得rawValue.你可以得到相关的价值.
原始问题:
我有一些用swift编写的通用反射代码.在该代码中,我无法获取基于枚举的属性的值.问题归结为我无法执行.rawValue属性类型的属性Any.Swift反射代码将返回枚举值作为类型Any.那么我怎样才能从Any到AnyObject,它是枚举的rawValue.
到目前为止,我发现的唯一解决方法是使用协议扩展所有枚举.您可以在下面看到使用此变通方法的单元测试.
有没有办法解决这个问题,而无需在原始枚举中添加代码?
对于我的反射代码,我需要getRawValue方法签名保持不变.
class WorkaroundsTests: XCTestCase {
func testEnumToRaw() {
let test1 = getRawValue(MyEnumOne.OK)
XCTAssertTrue(test1 == "OK", "Could nog get the rawvalue using a generic function")
let test2 = getRawValue(MyEnumTwo.OK)
XCTAssertTrue(test2 == "1", "Could nog get the rawvalue using a generic function")
let test3 = getRawValue(MyEnumThree.OK)
XCTAssertTrue(test3 == "1", "Could nog get the rawvalue using a generic function")
} …Run Code Online (Sandbox Code Playgroud) 我的应用程序有一个嵌入式APK,我需要BroadcastReceiver在我的主APK中注册内部APK.
内部APK不会安装在系统上; 我必须动态加载它.所以,我正在使用反射来调用内部APK中的方法,该方法具有注册的代码BroadcastReceiver.内部APK的接收器应该调用相关的广播.
我在尝试注册时遇到错误BroadcastReceiver.是否有可能以BroadcastReceiver这种方式注册,并且功能齐全?下面给出了例外和代码
错误相关日志:
08-24 08:31:26.915: D/MainApp(1957): invoke method
08-24 08:31:26.955: D/InnerApp(1957): Register receiver
08-24 08:31:26.955: W/System.err(1957): java.lang.reflect.InvocationTargetException
08-24 08:31:26.965: W/System.err(1957): at java.lang.reflect.Method.invokeNative(Native Method)
08-24 08:31:26.965: W/System.err(1957): at java.lang.reflect.Method.invoke(Method.java:515)
08-24 08:31:26.965: W/System.err(1957): at com.example.ea_mainapp.MainApp.invokeService(MainApp.java:105)
08-24 08:31:26.965: W/System.err(1957): at com.example.ea_mainapp.MainApp.onCreate(MainApp.java:40)
08-24 08:31:26.965: W/System.err(1957): at android.app.Activity.performCreate(Activity.java:5231)
08-24 08:31:26.975: W/System.err(1957): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-24 08:31:26.975: W/System.err(1957): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-24 08:31:26.975: W/System.err(1957): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-24 08:31:26.975: W/System.err(1957): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-24 08:31:26.975: W/System.err(1957): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-24 08:31:26.975: …Run Code Online (Sandbox Code Playgroud) 我正在尝试通过为Getter和Setter方法创建委托来改进我的反射代码.
我的代码看起来像这样:
MyObject obj = new MyObject();
var prop = obj.GetType().GetProperty("Prop");
var getType = typeof(Func<>).MakeGenericType(prop.PropertyType);
var setType = typeof(Action<>).MakeGenericType(prop.PropertyType);
var getMethod = prop.GetGetMethod().CreateDelegate(getType, obj);
var setMethod = prop.GetSetMethod().CreateDelegate(setType, obj);
// I'd like to change this section and not to use a dynamic!!
dynamic castedGet = Convert.ChangeType(getMethod, getType);
dynamic castedSet = Convert.ChangeType(setMethod, setType);
Run Code Online (Sandbox Code Playgroud)
CreateDelegate返回a Delegate并且使用DynamicInvoke 不是性能明智的.
我Delegate投入(硬编码)进入Action<T> \ Func<T>并看到我的表现大幅增加.
然后我试着投了Delegate到Action<T> \ Func<T>在运行时(使用Convert.ChangeType和dynamic …
使用反射时需要注意哪些潜在问题.我在反思中非常困惑,为什么java提供这种类型的功能来访问私有数据成员.
私有: 就像我想的那样,只有声明它的类才能看到它.
那为什么有可能访问其他类的私人事物?这个术语(反射)完全溢出了我在java中的private(Access Specifier)属性的概念.
我访问了许多有关此主题的链接,但没有给出关于此主题的完整说明.例如:
package example;
import java.lang.reflect.Method;
class A{
private void privateMethod(){
System.out.println("hello privateMethod()");
}
}
class B{
public static void main(String[] args) throws Exception {
A d = new A();
Method m = A.class.getDeclaredMethod("privateMethod");
m.setAccessible(true);
m.invoke(d);
}
}
Run Code Online (Sandbox Code Playgroud)
请详细解释这种方法的情景?我需要其他类中私有方法可访问性的优点和缺点吗?
例如,如果您运行以下代码...
Type IListType = new List<string>().GetType()
.GetInterface("IList`1")
.GetGenericTypeDefinition();
Run Code Online (Sandbox Code Playgroud)
...而且你看IListType变量,你会发现整个Type实例都有像FullName其他的一样可用的属性.
但是当你运行代码时会发生什么?
Type IListType2 = typeof(List<>).GetInterface("IList`1")
Run Code Online (Sandbox Code Playgroud)
现在IListType得到的泛型类型定义与第一个代码示例不同:大多数Type属性都将返回null.
这个问题的主要问题是IListType == IListType2它们是相同类型时不相等.
这是怎么回事?
现在看看如果你打电话会发生什么IListType2.GetGenericTypeDefinition()......它恢复了类型信息!
这将是巨大的,一个.NET Framework开发团队成员可以解释我们为何已经奇怪的失去了它的元数据已经泛型类型定义具有IsGenericTypeDefinition属性设置为false同时它还是一个泛型类型定义,最后,如果你调用GetGenericTypeDefinition()就可以了,你恢复类型信息.
以下等式将是true:
Type IListType = new List<string>().GetType()
.GetInterface("IList`1")
.GetGenericTypeDefinition();
// Got interface is "like a generic type definition" since it has
// no type for T generic parameter, and once you call
// …Run Code Online (Sandbox Code Playgroud)