Home > OS >  Java methods does return an object different from its declaration
Java methods does return an object different from its declaration

Time:04-29

I have a java method that returns an Optional<Long>:

Optional<Long> findOptionalRelation(String a, String b)

In the implementation there is a nativeQuery that counts results in a database:

  hqlBuilder.append("SELECT count(r.id)");
  hqlBuilder.append(" FROM RELATION r");
  hqlBuilder.append(" WHERE r.a = :a AND r.b = :b");
  final Query<Long> query = this.getCurrentSession().createNativeQuery(finalQuery);
            query.setParameter("a", a);
            query.setParameter("b", b);
            return query.uniqueResultOptional();

However, when I execute the method test, it returns an Optional<BigInteger> instead of an Optional<Long>.

After that, I did a test for myself with Optional<Long> longOpt = Optional.of(new BigInteger("0")); which of course cannot be cast.

How can I have bypassed the method return without breaking the execution?

Edit: this is the debugger:

Debugger

CodePudding user response:

You can convert Optional<BigInteger> to Optional<Long>:

Optional<Long> longOpt = Optional.of(new BigInteger("0")).map(BigInteger::longValue);

or

return query.uniqueResultOptional().map(BigInteger::longValue);

CodePudding user response:

The reason you didn't get a casting issue at runtime is due to type erasure, you can read about this feature on the docs or in other discussions. This mechanism essentially removes the generic type argument at compilation, meaning that at runtime it is not known.

  • Related