在Java中实例化scala.Int

时间:2013-02-18 20:24:10

标签: java scala playframework-2.0 scala-java-interop securesocial

我正在为Play 2框架的SecureSocial插件编写持久层。我在https://github.com/play-modules/modules.playframework.org/blob/master/app/models/ss/MPOOAuth2Info.java找到了一个例子:

package models.ss;

import models.AbstractModel;
import securesocial.core.java.OAuth2Info;
import javax.persistence.Entity;

@Entity
public class MPOOAuth2Info extends AbstractModel
{
    public String accessToken;

    public String tokenType;

    public Integer expiresIn;

    public String refreshToken;

    public MPOOAuth2Info()
    {
        // no-op
    }

    public MPOOAuth2Info(OAuth2Info oAuth2Info)
    {
        this.accessToken = oAuth2Info.accessToken;
        this.tokenType = oAuth2Info.tokenType;
        this.expiresIn = oAuth2Info.expiresIn;
        this.refreshToken = oAuth2Info.refreshToken;
    }

    public OAuth2Info toOAuth2Info()
    {
        OAuth2Info oAuth2Info = new OAuth2Info();

        oAuth2Info.accessToken = this.accessToken;
        oAuth2Info.tokenType = this.tokenType;
        oAuth2Info.expiresIn = this.expiresIn;
        oAuth2Info.refreshToken = this.refreshToken;

        return oAuth2Info;
    }
}

但API已更改,因此我无法使用securesocial.core.java.OAuth2Info。 SecureSocial由Scala编写,该类是Java前端。所以我决定直接在哪里使用Scala:

case class OAuth2Info(accessToken: String, tokenType: Option[String] = None,
                  expiresIn: Option[Int] = None, refreshToken: Option[String] = None)

我的结果:

package models.security.securesocial;

import models.AbstractModel;
import scala.Option;
import securesocial.core.*;

import javax.persistence.Entity;

/**
 * Persistence wrapper for SecureSocial's {@link } class.
 *
 * @author Steve Chaloner (steve@objectify.be)
 */
@Entity
public class MPOOAuth2Info extends AbstractModel
{
    public String accessToken;

    public String tokenType;

    public Integer expiresIn;

    public String refreshToken;

    public MPOOAuth2Info(){
        // no-op
    }

    public MPOOAuth2Info(OAuth2Info oAuth2Info){
        this.accessToken = oAuth2Info.accessToken();
        this.tokenType = oAuth2Info.tokenType().get();
        this.expiresIn = scala.Int.unbox(oAuth2Info.expiresIn().get());
        this.refreshToken = oAuth2Info.refreshToken().get();
    }

    public OAuth2Info toOAuth2Info(){
        return new OAuth2Info(accessToken, Option.apply(tokenType), Option.apply(SOME_TRANSFORMATION(expiresIn)), Option.apply(refreshToken));
    }
}

但我将scala.Int转换为java.lang.Integer类型的问题存在问题。 要将scala.Int转换为java.lang.Integer我使用scala.Int.unbox()。是连接方式吗?我不知道如何将java.lang.Integer转换为scala.Int:在代码中我输入了伪代码SOME_TRANSFORMATION()。这个SOME_TRANSFORMATION的正确实现是什么?

谢谢

2 个答案:

答案 0 :(得分:5)

scala.Int.unbox(new java.lang.Integer(3))提供Int = 3

scala.Int.box(3)提供Integer = 3

答案 1 :(得分:3)

Scala框和自动透明地取消装箱。此外,scala.Int有点虚构。当存储在局部变量中,作为形式参数传递或存储在类中时,它是本机int(例如Java / JVM)。但是当它必须通过参数化/泛型类型的值进行交易时,必须将其装箱并取消装箱。 (有一个例外,当有问题的类型参数是专门的,但这是另一个故事。)