[salesforce apex] apex 中生成随机码

2023-04-26 10:12:29 浏览数 (3)

如果想要生成一次性访问code,可以参考如下:

返回String方式:

代码语言:txt复制
 * @param length The number of digits to return
 * @return a random number the length of the input param length
 * @description one limitation, will never start with 0
 */
public static String generateRandomNumber(Integer length) {
    String result = '';
    while(result.length() < length){
       //Math.abs used to cast Crypto.getRandomLong() to a positive number
       result  = String.valueOf(Math.abs(Crypto.getRandomLong()));
    }
    return result.substring(0,length);
}

返回Integer方式

代码语言:txt复制
 * @param length The number of digits to return
 * @return a random number the length of the input param length
 * @description one limitation, will never start with 0
 */
public static String generateRandomNumber(Integer length) {
    String result = '';
    while(result.length() < length){
       //Math.abs used to cast Crypto.getRandomLong() to a positive number
       result  = String.valueOf(Math.abs(Crypto.getRandomLong()));
    }
    return Integer.valueOf(result.substring(0,length));
}

使用 Math.Random() 生成随机数

代码语言:txt复制
//Generate a random Double between 0 and 1
System.debug(Math.Random());
//Prints e.g. 0.3128804447173097 

//Generate a random Double between 0 and 10
System.debug(Math.Random() * 10);
//Prints e.g. 5.235707559078412

//Generate a random Integer between 0 and 10
System.debug(Integer.valueOf(Math.Random() * 10));
//Prints e.g. 5

//Generate a random Integer between 0 and 100
System.debug(Integer.valueOf(Math.Random() * 100));

使用加密类生成随机整数

代码语言:txt复制
System.debug(Crypto.getRandomInteger());
//prints e.g. -1608518142

此文章link:

https://www.levelupsalesforce.com/apex-generate-random-number

0 人点赞