/* * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package vm.mlvm.meth.share; public class PrimitiveTypeConverter { /** Unbox, cast and box */ public static Object cast(Object fromValue, Class toType) { Class fromType = fromValue.getClass(); # # String[] ptypes = new String[] { "byte", "short", "char", "int", "long", "float", "double" }; # String[] btypes = new String[] { "Byte", "Short", "Character", "Integer", "Long", "Float", "Double" }; # # for ( int f = 0; f < ptypes.length; f++ ) { # String fb = btypes[f]; # String fp = ptypes[f]; # for ( int t = 0; t < ptypes.length; t++ ) { # String tp = ptypes[t]; # String tb = btypes[t]; if ( @fb.class.equals(fromType) && toType.equals(@tp.class) ) # # if ( f == t ) { # return fromValue; # # } else { # return @tb.valueOf((@tp) ((@fb) fromValue).@(fp)Value()); # # } # } # } throw new IllegalArgumentException("Can't cast [" + fromValue + "] to " + toType); } /** Unbox, do primitive widening conversion (JLS 5.1.2) and box */ public static Object convert(Object fromValue, Class toType) { Class fromType = fromValue.getClass(); # # for ( int t = 0; t < ptypes.length; t++ ) { # String tp = ptypes[t]; # String tb = btypes[t]; # # if ( tp.equals("char") ) continue; # if ( @tb.class.equals(fromType) && toType.equals(@tp.class) ) return fromValue; # # for ( int f = 0; f < t; f++ ) { # String fp = ptypes[f]; # String fb = btypes[f]; if ( @fb.class.equals(fromType) && toType.equals(@tp.class) ) return @tb.valueOf((@tp) ((@fb) fromValue).@(fp)Value()); # } # } throw new IllegalArgumentException("Can't convert [" + fromValue + "] to " + toType); } }