📌  相关文章
📜  Java中的 CompoundName getPrefix() 方法和示例

📅  最后修改于: 2022-05-13 01:54:34.406000             🧑  作者: Mango

Java中的 CompoundName getPrefix() 方法和示例

javax.naming.CompoundName 类getPrefix()方法用于获取复合名称对象,其组件由该复合名称中的组件的前缀组成。我们需要停止从该复合名称对象中提取前缀的位置作为参数传递。返回的复合名称对象和此复合名称对象共享相同的语法。如果我们对此复合名称进行任何不会影响返回的名称的更改,反之亦然。

句法:

public Name getPrefix(int posn)

参数:此方法接受 posn,它是要停止的组件的从 0 开始的索引。必须在 [0, size()] 范围内。

返回值:此方法返回一个复合名称,该名称由索引范围 [0, posn) 处的组件组成。

异常:如果 posn 超出指定范围,则此方法抛出ArrayIndexOutOfBoundsException

下面的程序说明了 CompoundName.getPrefix() 方法:
方案一:

// Java program to demonstrate
// CompoundName.getPrefix()
  
import java.util.Properties;
import javax.naming.CompoundName;
import javax.naming.InvalidNameException;
  
public class GFG {
    public static void main(String[] args)
        throws InvalidNameException
    {
  
        // need properties for CompoundName
        Properties props = new Properties();
        props.put("jndi.syntax.separator", "@");
        props.put("jndi.syntax.direction",
                  "left_to_right");
  
        // create compound name object
        CompoundName CompoundName1
            = new CompoundName(
                "1@2@3@4@5@6@7",
                props);
  
        // apply getPrefix()
        CompoundName newCompoundName
            = (CompoundName)
                  CompoundName1
                      .getPrefix(3);
  
        // print value
        System.out.println(
            "New CompoundName Object: "
            + newCompoundName);
    }
}
输出:
New CompoundName Object: 1@2@3

方案二:

// Java program to demonstrate
// CompoundName.getPrefix() method
  
import java.util.Properties;
import javax.naming.CompoundName;
import javax.naming.InvalidNameException;
  
public class GFG {
    public static void main(String[] args)
        throws InvalidNameException
    {
  
        // need properties for CompoundName
        Properties props = new Properties();
        props.put("jndi.syntax.separator", "/");
        props.put("jndi.syntax.direction",
                  "left_to_right");
  
        // create compound name object
        CompoundName CompoundName1
            = new CompoundName(
                "c/e/d/v/a/b/z/y/x/f",
                props);
  
        // apply getPrefix()
        CompoundName newCompoundName
            = (CompoundName)
                  CompoundName1.getPrefix(8);
  
        // print value
        System.out.println(
            "New CompoundName Object: "
            + newCompoundName);
    }
}
输出:
New CompoundName Object: c/e/d/v/a/b/z/y

参考资料:https://docs.oracle.com/javase/10/docs/api/javax/naming/CompoundName.html#getPrefix(int)