Java通用lambda调用(Java generic lambda call)

我有一个类,在构造函数中有一个接口对象:

private Operator(/* ..., */ final Operation<?> operation) {
    //...
}

Operation是一个通用接口,有一个方法:

@SuppressWarnings("unchecked")
public T applyOperation(T... arguments);

我现在可以像这样创建一个类操作符的Object:

public static final Operator POSTFIX_INCREASE = new Operator(/* ...,*/ new Operation<Integer>() {

    @Override
    public Integer applyOperation(Integer... arguments) {
        return arguments[0]++;
    }
});

但我想用lambda表达式来做这个。 这是eclipse本身重新评估的内容(到目前为止看起来很好):

public static final Operator POSTFIX_INCREASE = new Operator("++", 0, 1, true, arguments -> arguments[0]++);

唯一的问题......它不起作用:D当然我知道,我需要提供类型信息:我需要一个操作员界面的整数实现。 在匿名类中,我可以提供默认方式,但在lambda表达式中,这是不可能的。 有没有办法写一个通用的lambda表达式,还是不支持它? (这不会是一个大惊喜,因为泛型在java中不是很灵活)


I got a class, that has a Interface Object in the constructor:

private Operator(/* ..., */ final Operation<?> operation) {
    //...
}

Operation is a generic interface with one method:

@SuppressWarnings("unchecked")
public T applyOperation(T... arguments);

I can now create an Object of class Operator like this:

public static final Operator POSTFIX_INCREASE = new Operator(/* ...,*/ new Operation<Integer>() {

    @Override
    public Integer applyOperation(Integer... arguments) {
        return arguments[0]++;
    }
});

But I'd like to this with a lambda expression. This is what eclipse itself reconmends (And it looks good so far):

public static final Operator POSTFIX_INCREASE = new Operator("++", 0, 1, true, arguments -> arguments[0]++);

The only problem... It does not work :D Of course I know, i need to provide type information: I need an integer implementation of the Operator interface. In the anonymous class I can just provide it the default way, but in a lambda expression, this isn't possible. Is there any way to write a generic lambda expression, or don't they support that? (what wouldn't be a big surprise, since generics aren't very flexible in java)


原文:https://stackoverflow.com/questions/36956635
2023-12-14 21:12

满意答案

我也是CoreData的新手,但在我看来,谓词是错误的。 根据日志记录,您将personToDepartment.departmentName与部门对象进行比较。 谓词应该如下所示: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"personToDepartment.departmentName = %@", selectedDepartment.departmentName];

但还有更好的方法。 selectedDepartment.departmentToPerson将返回一个NSSet,其中包含属于该部门的所有人员(如果先前已设置了关系)。 但是警告,如果你要尝试NSLog(@"%@", selectedDepartment.departmentToPerson)你可能会得到“ 关系错误 ”,因为在你通过NSSet寻址特定对象或通过它枚举之前,CoreData不会进行获取。 但是例如NSLog(@"%d", selectedDepartment.departmentToPerson.count)将强制CoreData进行获取,你将看到部门中的人数。

更新:NSSet为空可能是因为您在创建人物对象时没有设置关系。 将自动设置从部门到人员的反向To-Many关系。

- (id)insertNewPerson:(NSDictionary *)personInfo inDepartment:(Department*)departmentObject 
{
    Person *personObject = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
    personObject.name = personInfo.name;
    personObject.departmentName = departmentObject.name;
    ...
    personObject.personToDepartment = departmentObject;   //this is RELATIONSHIP, if set, then you can access all persons from specific department by doing: departmentObject.departmentToPerson
}

I'm also kind of newbie to CoreData, but it seems to me that predicate is wrong. According to Log record you're about to comparing personToDepartment.departmentName to a department Object. Predicate should look like: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"personToDepartment.departmentName = %@", selectedDepartment.departmentName];

But there is a better way. selectedDepartment.departmentToPerson will return an NSSet with all persons belonging to this department (if relationship was set previously). But warning, if you'll try to NSLog(@"%@", selectedDepartment.departmentToPerson) probably you'll get "relationship fault", because CoreData will not do fetch until you address specific object in NSSet or enumerate through it. But for example NSLog(@"%d", selectedDepartment.departmentToPerson.count) will force CoreData to make fetch and you'll see number of persons in department.

UPDATE: NSSet is empty probably because you are not setting relationship, when creating person's object. Inverse To-Many relationship from department to persons will be set automatically.

- (id)insertNewPerson:(NSDictionary *)personInfo inDepartment:(Department*)departmentObject 
{
    Person *personObject = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
    personObject.name = personInfo.name;
    personObject.departmentName = departmentObject.name;
    ...
    personObject.personToDepartment = departmentObject;   //this is RELATIONSHIP, if set, then you can access all persons from specific department by doing: departmentObject.departmentToPerson
}

相关问答

更多

CoreData - 一对多关系(CoreData - One-to-many relationship)

您要执行的操作的文档位于此链接的“To-Many Relationships”标题下。 这是一个简短的例子。 首先,我建议将您的关系名称更改为更直观的内容。 它真的会有所帮助: class TrainingDay: NSManagedObject { @NSManaged var day: String @NSManaged var trainingDetails: NSSet } class TrainingDetails: NSManagedObject { // ....

具有一对多关系的NSFetchedResultsController(NSFetchedResultsController with one-to-many relationship)

您的数据模型应具有互惠关系,以便在获取任何特定对象时,您可以立即访问所有相关对象。 在您的情况下,具有互惠关系的数据模型看起来像: City{ company<-->Company.city } Company{ city<-->City.company employees<-->>Employee.company } Employee{ company<<-->Company.employees } 因此,如果您有一个Employee对象,您可以找到self...

约束一对多关系(Constraint for one-to-many relationship)

从模式的角度来看,这种约束是不可能的,因为你遇到了“鸡还是蛋”类型的场景。 在这种情况下,当我插入到父表中时,我必须在子表中有一行,但在父表中有一行之前,我不能在子表中有一行。 这是更好地执行客户端。 Such a constraint isn't possible from a schema perspective, because you run into a "chicken or the egg" type of scenario. Under this sort of scenario,...

iPhone Core Data关系错误(iPhone Core Data relationship fault)

“错误”并不意味着错误,它只是意味着返回的对象是一个“幽灵”而没有读入其属性。为关系的另一方获取错误是正常的,因为你没有设置的提取通过其关系从一个不受控制的对象创建级联。 当您访问故障的属性时,它将作为一个功能齐全的对象出现故障。 编辑: 来自评论: 问题是我通过NSLog请求这种关系,但我仍然无法得到关系实体。 不你不是。 您只需要自己请求Items实体然后记录它们。 他们按照预期为他们的关系返回错误。 只有当你问每一个关系另一边的实际对象时,你才能保证看到一个对象而不是一个错误。 这就是你需要...

ORMLite自身的一对多关系(ORMLite one-to-many relationship of itself)

我似乎通过将private ForeignCollection<Route>替换为Collection<Route>来解决了这个问题。 如果我使用ForeignCollection作为类型,我不太确定为什么它不起作用,但它似乎解决了我所有的问题。 I seemed to have solved the issue by replacing private ForeignCollection<Route> to just Collection<Route>. I'm not quite sure w...

将NSManagedObjects添加到一对多关系中(Adding NSManagedObjects to a one-to-many relationship)

您无法直接向集合添加对象。 您需要使用Core Data生成的访问者或您自己的自定义访问者。 查看.h文件,您应该看到类似的内容 -(void)addClsObject:(Cls *)theObject; 和 -(void)addClsObjects:(NSSet *)set; 因此,对于您的特定情况,您将在拥有Cls对象后执行以下操作: [student addClassesObject:cls]; 然后执行保存,您应该能够检索设置的类。 仅供参考,调用此方法和relatd NSSet r...

识别一对多关系(Identifying one-to-many relationship)

如果城市的密钥是(country_id,city_id),那么关系是“识别” - 意味着主键部分或全部是对另一个表的外键引用。 如果country_id不是主键的一部分,那么它是非标识的。 这两个不同的键会使表格在每种情况下代表非常不同的东西,但只有你可以说哪个更适合你的要求。 不要过分担心识别与非识别关系的概念。 这是一个源于ER建模的概念,但在关系数据库设计中,它通常具有很小的实际意义。 If the key of cities is (country_id, city_id) then th...

添加setRelationshipKeyPathsForPrefetching后仍然显示获取一对多关系错误(Fetch one-to-many relationship fault still shows after adding setRelationshipKeyPathsForPrefetching)

我也是CoreData的新手,但在我看来,谓词是错误的。 根据日志记录,您将personToDepartment.departmentName与部门对象进行比较。 谓词应该如下所示: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"personToDepartment.departmentName = %@", selectedDepartment.departmentName]; 但还有更好的方法。 selectedDepa...

如何管理Core Data中的一对多关系?(How to manage one-to-many relationship in Core Data?)

如何创建帐户和部门对象以便建立一对多的关系? 如果您在模型中配置了核心数据,核心数据将自动为您填充反向关系。 因此,根据您构建代码的方式,您可以将newAccount.department = aDepartment; 你的关系和逆都被创造了。 我应该怎么做CoreDataGeneratedAccessors?创建之后,我应该调用CachedDepartment的-addAddressesObject函数,还是需要创建类似anAccount.department = aDepartment东西,那...

以一对多关系在列上创建索引(Create index on column in one-to-many relationship)

起初我没有得到你想要的东西,但我想我弄清楚了。 您定义了list-index ,用于保存java.util.List的索引,而不是Child的parent_id。 所以你正在寻找如何创建真正的数据库索引。 这可以通过这样的注释轻松完成; @OneToMany(cascade = { CascadeType.ALL }) @JoinColumn(name="parent_id") @Index(name = "idx_parent_id", columnNames = "parent_id") pr...

相关文章

更多

java lambda表达式-JAVA8新特性

Lambda概述 lambda表示数学符号“λ”,计算机领域中λ代表“λ演算”,表达了计算机中最基本 ...

怎样用Struts2的lambda表达式取一个map集合的子集

前台的jsp代码是这样的。 &lt;s:select cssStyle=&quot; width:2 ...

Hadoop源码分析之二(RPC机制之Call处理)

上一篇介绍整个RPC Server端的处理机制。http://www.linuxidc.com/Lin ...

Hadoop源码分析之RPC(Remote Procedure Call Protocol)

理解这个RPC是不是的先去理解哈动态代理 好多invoke,还有Socket网络编程 先来张eclip ...

Solr Cache使用介绍及分析,包括LRUCache、filterCache、queryResultCache、documentCache、Generic Caches

本文将介绍Solr查询中涉及到的Cache使用及相关的实现。Solr查询的核心类就是SolrIndex ...

[Hadoop Err] Call to ? failed on local exception: java.net.NoRouteToHostException: No route to host

表现: 如果你 grep datanode 的 log 发现了这个 Error,原文如下: Hadoo ...

java 调用oracle的存储过程返回记录集

从oracle存储过程返回记录集 转自:http://www.cnblogs.com/SunJav ...

java 调用oracle的存储过程返回记录集

从oracle存储过程返回记录集 转自:http://www.cnblogs.com/jinan ...

java通用返回对象

java通用返回对象返回对象通常包括是否成功、响应码、接口响应描述、响应实体几个属性

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本