Java中的方法类| isBridge()方法

这个 JAVA朗,反思 方法伊斯布里奇() 方法用于检查函数是否为桥接函数。如果方法对象是桥方法,则此方法返回true,否则返回false。

null

桥接方法: 这些方法在源函数和目标函数之间创建一个中间层。它通常用作类型擦除过程的一部分。这意味着桥接方法需要作为类型安全接口。

例如,在下面的示例中,compare()方法 对象 as参数表现为桥接方法。它将铸造 对象 一串 并调用以字符串为参数的比较函数。所以 比较(对象a、对象b) 充当源(调用compare()的方法)和目标(compare(String,String))之间的桥梁。

例子:

public class compareValues implements Comparator {

   // target method
   public int compare(String a, String b) 
   {
   }
   
   // bridge method
   public int compare(Object a, Object b) {
      return compare((String)a, (String)b);
   }
}

语法:

public boolean isBridge()

返回值: 此方法返回 符合事实的 如果方法对象是JVM规范中的桥接方法,则返回 错误的 .

下面的程序演示了method类的isBridge()方法:

项目1: 程序返回BigInteger类的所有桥接方法。

说明: 在这个方法中,首先创建BigInteger类对象。创建对象后,通过调用类对象的getMethods()创建方法对象列表。现在,对获取的方法列表进行迭代并检查isBridge()。因此我们得到了桥接方法。最后打印桥接方法名称。

/*
* Program Demonstrate isBridge() method
* of Method Class.
*/
import java.lang.reflect.Method;
import java.math.BigInteger;
public class GFG {
// create main method
public static void main(String args[])
{
try {
// create BigInteger class object
Class bigInt = BigInteger. class ;
// get list of Method object
Method[] methods = bigInt.getMethods();
System.out.println( "Bridge Methods of BigInteger Class are" );
// Loop through Methods list
for (Method m : methods) {
// check whether the method is Bridge Method or not
if (m.isBridge()) {
// Print Method name
System.out.println( "Method: " + m.getName());
}
}
}
catch (Exception e) {
// print Exception is any Exception occurs
e.printStackTrace();
}
}
}


输出:

Bridge Methods of BigInteger Class are
Method: compareTo

项目2: 检查是否有自定义方法isBridge()。

说明: 当子类从父类继承方法时,继承的方法将充当桥接方法。在这段代码中,首先创建一个包含draw方法的Shape类,然后创建一个扩展Shape类的矩形类。在main方法中,创建了矩形类的draw方法的方法对象。现在检查它是否为bridge()方法。最后打印结果。

// Program Demonstrate isBridge() method
// of Method Class.
// In this program a custom bridge method is created
// and by use of isBridge(), checked for Bridge Method
import java.lang.reflect.Method;
public class GFG {
// create class
protected class Shape {
public void draw() {}
}
// create a class which extends Shape class
public class Rectangle extends Shape {
}
// create main method
public static void main(String args[])
{
try {
// create class object for class
// Rectangle and get method object
Method m = Rectangle. class .getDeclaredMethod( "draw" );
// check method is bridge or not
boolean isBridge = m.isBridge();
// print result
System.out.println(m + " method is Bridge Method :"
+ isBridge);
}
catch (NoSuchMethodException | SecurityException e) {
// Print Exception if any Exception occurs
e.printStackTrace();
}
}
}


输出:

public void GFG$Rectangle.draw() method is Bridge Method :true

参考: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#isBridge– https://stackoverflow.com/questions/5007357/java-generics-bridge-method http://stas-blogspot.blogspot.com/2010/03/java-bridge-methods-explained.html

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享