com.mysema.query.support.NumberConversions Maven / Gradle / Ivy
/*
* Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.query.support;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Maps;
import com.mysema.query.types.Expression;
import com.mysema.query.types.FactoryExpression;
import com.mysema.query.types.FactoryExpressionBase;
import com.mysema.query.types.Visitor;
import com.mysema.util.MathUtils;
/**
* NumberConversions ensures that the results of a projection involving numeric expressions
* confirm to the types of the numeric expressions
*
* @author tiwe
*
* @param
*/
public class NumberConversions extends FactoryExpressionBase {
private static final long serialVersionUID = -7834053123363933721L;
private final FactoryExpression expr;
private final Map, Enum>[]> values = Maps.newHashMap();
public NumberConversions(FactoryExpression expr) {
super(expr.getType());
this.expr = expr;
}
@Override
public R accept(Visitor v, C context) {
return v.visit(this, context);
}
@Override
public List> getArgs() {
return expr.getArgs();
}
private > Enum[] getValues(Class enumClass) {
Enum[] values = (Enum[]) this.values.get(enumClass);
if (values == null) {
try {
values = (Enum[]) enumClass.getMethod("values").invoke(null);
this.values.put(enumClass, values);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
return values;
}
@Override
public T newInstance(Object... args) {
for (int i = 0; i < args.length; i++) {
Class> type = expr.getArgs().get(i).getType();
if (Enum.class.isAssignableFrom(type) && !type.isInstance(args[i])) {
if (args[i] instanceof String) {
args[i] = Enum.valueOf((Class)type, (String)args[i]);
} else if (args[i] instanceof Number) {
args[i] = getValues((Class)type)[((Number)args[i]).intValue()];
}
} else if (args[i] instanceof Number && !type.isInstance(args[i])) {
if (type.equals(Boolean.class)) {
args[i] = ((Number)args[i]).intValue() > 0;
} else if (Number.class.isAssignableFrom(type)){
args[i] = MathUtils.cast((Number)args[i], (Class)type);
}
}
}
return expr.newInstance(args);
}
}