方法重载最少的特定方法参数类型

时间:2017-11-06 06:48:34

标签: java

public class Class1 {

    public void method(Object obj){
        System.out.println("Object");
    }

    public void method(String str){
        System.out.println("String");
    }

    public static void main(String... arg){
        new Class1().method(null);
    }

}

根据JVM,它将调用最具体的参数类型,在这种情况下,最具体的是String,因此方法调用发生在字符串参数类型,但我们需要调用Object参数类型的方法

2 个答案:

答案 0 :(得分:2)

你可以将null转换为字符串或对象来调用你的一个方法null是String的默认值,所以它在你的代码中调用String方法

<!-- The drawing color for the bars -->
<attr name="color" format="color"/>
<!-- Whether bars should rotate or not during transition -->
<attr name="spinBars" format="boolean"/>
<!-- The total size of the drawable -->
<attr name="drawableSize" format="dimension"/>
<!-- The max gap between the bars when they are parallel to each other -->
<attr name="gapBetweenBars" format="dimension"/>
<!-- The length of the arrow head when formed to make an arrow -->
<attr name="arrowHeadLength" format="dimension"/>
<!-- The length of the shaft when formed to make an arrow -->
<attr name="arrowShaftLength" format="dimension"/>
<!-- The length of the bars when they are parallel to each other -->
<attr name="barLength" format="dimension"/>
<!-- The thickness (stroke size) for the bar paint -->
<attr name="thickness" format="dimension"/>

答案 1 :(得分:0)

您可以通过将Object强制转换为null来强制编译器选择采用Object参数的方法:

new Class1().method((Object)null);