Salesforce之變量基礎知識,集合,表達式,流程控制語句

  salseforce 如果簡單的說可以大概分成兩個部分 : Apex 和 VisualForce  Page.

  其中Apex語言 和 Java 有很多的語法類似,我們今天之總結一些簡單的Apex的變量等知識 .  詳細知識的話可以參考 Apex教程

我們在Apex中常用的基本變量有  

          Integer , String , Decimal , Double , Long , Boolean , ID

   集合常用的對象有 

        List <T> , Set<T> , Map<T>

  時間日期常用對象有

        Datetime , TIme , Date 

   其他 :

     Object , sObejct (與數據庫相關 , 後面會講)

注意 : Apex與Java最大的區別就是 Apex中基本對象的初始值均爲 null 值. 

Integer i;
i += 1;
System.debug(i);

在java中此種寫法是可以的,因爲int類型初始值爲0,i+=1以後則i變成1.但是在Apex中因爲i初始值爲null。
所以i+=1在運行時會拋出NullPointerException
當然,比較有意思的事情是這樣,直接上代碼:

Integer i;
System.debug(i+'1');

此種方法輸出的結果則爲null1。起始這也不奇怪,因爲Apex也是基於java拓展的,如果看java編程思想了解底層的null的toString()方法處理也就知道了,當執行Print操作時,一個變量爲null時,他的toString方法則返回'null'字符串。當然,這個只是一個拓展,不多展開,如果感興趣,可以查看一下java的api或者看一下java編程思想一書。

一 . 基本變量

    1. Integer 

    Integer 表示一個32位整數的對象 , 取值範圍爲-2^31 -- 2^31.

   Integer 主要有2個方法 :

/*
    public String format()
    //譯:將Integer值轉換成String類型的值
 */
Integer goodsCount = 12;
System.debug('將Integer值轉成String: ' + goodsCount.format());
/*
   public static Integer valueOf(String stringToObject)
   //譯:將String類型轉成Integer類型
*/
Integer goodsCountI = Integer.valueOf('12');

     2. Long

Long類型表示一個64位整數的對象,取值範圍爲-2^63 -- 2^63-1.

Integer類型的值可以直接轉換成Long類型的,Long類型在不超過範圍情況下可以通過intValue() 方法轉成Integer類型 .

Long類型部分主要方法 :

Integer transferSource = 12345;<br>Long code = transferSource;//Integer類型可以直接轉成Long類型
/*
   public String format()
   //譯:將Long類型轉換成String類型
*/
System.debug('Long類型轉成String類型:' + code.format());
/*
   public Integer intValue()
   //譯:將Long類型轉成Integer類型
*/
   System.debug('將Long類型轉成Integer類型:' + code.intValue());          
/*
   public static Long valueOf(String stringToLong)
   //譯:將String類型轉成Long類型
*/
Long codeLong = Long.valueOf('123');

     3.ID

 ID類型可以用任意一個符合規則的18位字符表示,如果想要設置ID字符爲15位的話,則會將字符自定擴展爲18位 . 不符合規則的ID字符在運行時會拋出異常.

    ID類型的主要方法 :

/*
    public static ID valueOf(String toID)
    //譯:將toId轉換成ID
*/
String idStr = '111111111111111111';
ID id = ID.valueOf(idStr);
/*
   public Boolean equals(String id)
   //譯:判斷兩個ID是否相同
*/
Boolean isEquals = id.equals(idStr);

       4.Decimal

   包含小數點的32位數就是Decimal,類似於Java中的float類型的變量.

  Decimal 類型的主要方法 :

Decimal priceDecimal = -4.50;
 /*
    public Decimal abs()
    //譯:返回小數點的絕對值
 */
 System.debug('小數的絕對值爲:' + priceDecimal.abs());
            
 /*
    public Decimal divide(Decimal divisor, Integer scale)
    //譯:通過divisor作爲除數,並設置結果爲特定的scale的位數
 */
 System.debug('priceDecimal除以10小數點保留兩位小數: ' + priceDecimal.divide(10,2));//-0.45
            
 /*
    public Double doubleValue()
    //譯:將Decimal類型轉換成Double類型
 */
 System.debug('將priceDecimal轉換成Double類型' + priceDecimal.doubleValue());
            
 /*
    public String format()
    //譯:將Decimal轉成String類型
 */
 System.debug('Decimal轉成String類型' + priceDecimal.format());
            
 /*
    public Integer intValue()
    //譯:將Decimal轉成Integer
 */
 System.debug('將Decimal轉成Integer類型' + priceDecimal.intValue());
            
 /*
    public Long longValue()
    //譯:將Decimal轉成Long類型
 */
 System.debug('將Decimal轉成Long類型' + priceDecimal.longValue());
            
 /*
    public Decimal pow(int exponent)
    譯:返回Decimal對應的指數次冪值.如果Decimal值爲0,則返回1
 */
 System.debug('priceDecimal平方值爲:' + priceDecimal.pow(2));
            
 /*
    public Integer precision()
    //譯:返回Decimal值得數字的總數
 */
 System.debug('priceDecimal數字總數爲:' + priceDecimal.precision());//2   -4.5  有4和5
            
            
 /*
    public Long round()
    //譯:將Decimal值轉換成最接近Long類型的值,四捨五入
 */
 System.debug('priceDecimal四捨五入Long類型值爲:' + priceDecimal.round());
            
 /*
    public Integer scale()
    //譯:返回小數點後的位數個數
 */
 System.debug('priceDecimal小數點後的位數爲:' + priceDecimal.scale());
            
 /*
    public Decimal setScale(Integer scale)
    //譯:設置小數的小數點後的位數
 */
 System.debug('設置priceDecimal的小數爲2位' + priceDecimal.setScale(2));
            
 /*
    public Decimal stripTrailingZeros()
    //譯:返回移除0以後的小數
 */
 System.debug('移除priceDecimal小數點後的0以後的值爲:' + priceDecimal.stripTrailingZeros());
            
 /*
    public String toPlainString()
    //譯:返回Decimal轉換後的String,Decimal值不使用科學記數法
 */
 System.debug('不使用科學記數法轉換成String類型' + priceDecimal.toPlainString());
 /*
    Decimal.valueOf(Object objectToDecimal)
    //譯:將Object轉成Decimal。其中Object可以爲Double,Long,             String
 */
 Long priceL = 12345;
 Double priceD = 123.456;
 String priceS = '12345';
 Decimal d1 = Decimal.valueOf(priceL);
 Decimal d2 = Decimal.valueOf(priceD);
 Decimal d3 = Decimal.valueOf(priceS);

           5. Double

    包含小數點的64位數就是Double,類似於Java中的Double類型的變量.

Decimal類型變量可以直接轉換成Double類型變量,Double類型在不超過範圍情況下可以通過

以下爲Double 的部分主要方法 ;

Double price = 34.5678;
/*
   public static Double valueOf(String stringToDouble)
   //譯:將String類型轉換成Double
*/
String doubleString = '3.89';
System.debug('將字符串轉換成Double' + Double.valueOf(doubleString));
         
/*
   public Long round()
   //譯:返回double最接近Long的值,四捨五入
*/
Long priceLong = price.round();
System.debug('通過round方法將double轉換成Long類型值爲:' + priceLong);
         
/*
   public Integer intValue()
   //譯:將double值轉換成int類型值
*/
Integer priceInteger = price.intValue();
System.debug('將double轉換成Integer類型值爲:' + priceInteger);
Long priceLongByLongValue = price.longValue();
System.debug('將double轉換成Long類型值爲:' + priceLongByLongValue);

                6.String

String類型和Java中的String類型很類似,在這裏不做過多解釋,代碼中主要需要看一下String類型對象和上述變量如何相互轉換,這在項目中是經常用到的,也是必須需要知道的。以下爲String類型主要方法:

String goodsName = 'abcd123漢字顯示';//測試文本
 /*
    public String abbreviate(Integer maxWidth)
    //譯:返回簡化字符串,maxWidth>自身長度?自身:maxWidth長度的字符串加上省略號,省略號佔3個字符
    //注意:maxWidth如果小於4,則拋出Runtime Exception
 */
         
 System.debug('簡化後的字符串名稱爲: '+goodsName.abbreviate(5));//結果:ab...
            
 /*
    public String abbreviate(Integer maxWidth,Integer offset)
    //譯:返回簡化字符串,maxWidth爲需要簡化長度,offset爲字符串簡化起點
    //如果max太小,則拋出Runtime Exception
 */
    //返回簡化字符串,參數1:最大長度;參數2:偏移量offset
 System.debug('簡化並添加偏移量的字符串名稱爲:'+goodsName.abbreviate(5,2));
            
 /*
    public String capitalize()
    //譯:返回當前字符串,其中第一個字母改爲標題(大寫)。
 */
            
 System.debug('將首字母大寫顯示'+goodsName.capitalize());
            
 /*
    public String center(Integer size)
    //譯:返回指定大小字符串使原字符串位於中間位置(空格填充左右),如果size<字符串長度,則不起作用
 */
            
   System.debug('設置指定字符串長度爲20的顯示爲:' + goodsName.center(20));
            
 /*
    public String center(Integer size,String paddingString)
    //譯:返回指定大小字符串使原字符串處於中間位置。參數1:字符串顯示長度;參數2:填充的字符樣式
 */
   //返回值:----abcd123漢字顯示-----
 System.debug('使用-填充字符串顯示爲:'+goodsName.center(20,'-'));
            
 /*
    public Integer charAt(Integer index)
    //譯:返回對應值得ASC碼值
 */
 System.debug('goodsName.charAt(5)' + goodsName.charAt(5));
            
 /*
    public Integer codePointAt(Integer index)
    //譯:返回指定位置的值對應的Unicode編碼
 */
            
 System.debug('goodsName.codePoint(5)' + goodsName.codePointAt(5));
            
 /*
    public Integer codePointBefore(Integer index)
    //譯:返回指定位置的值前一個對應的Unicode編碼
 */
 System.debug('goodsName.codePointBefore(5)' + goodsName.codePointBefore(5));
            
 /*
    public Integer codePointCount(Integer beginIndex,Integer endIndex)
    //譯:返回起始位置到截至位置字符串的Unicode編碼值
 */
            
 System.debug('goodsName.codePointCount(5,7)' + goodsName.codePointCount(5,7));
            
 /*
    public Integer compareTo(String secondString)
    //譯:基於Unicode比較兩個字符串大小,如果小於比較值返回負整數,大於返回正整數,等於返回0
 */
 System.debug('兩個字符串比較的情況爲 : ' + goodsName.compareTo('compareString'));
            
 /*
    public Boolean contains(String substring)
    //譯:判斷是否包含某個字符串,包含返回true,不包含返回false
 */
            
 System.debug('商品名稱是否包含abcd : ' + goodsName.contains('abcd'));
            
 /*
    public Boolean containsAny(String inputString)
    //譯:判斷是否包含inputString任意一個字符,包含返回true,不包含返回false
 */
 System.debug('商品名稱是否包含abcd任意一個字符:' + goodsName.containsAny('abcd'));
            
 /*
    public Boolean containsIgnoreCase(String inputString)
    //譯:判斷是否包含inputString(不區分大小寫),包含返回true,不包含返回false
 */
            
 System.debug('商品名稱是否包含AbCd(不區分大小寫:)' + goodsName.containsIgnoreCase('AbCd'));
 /*
    public Boolean containsNone(String inputString)
    //譯:判斷是否不包含inputString,不包含返回true,包含返回false
 */
 System.debug('商品名稱是否不包含abcd'+goodsName.containsNone('abcd'));
            
 /*
    public Boolean containsOnly(String inputString)
    //譯:當前字符串從指定序列只包括inputString返回true,否則返回false
 */
 System.debug('商品名稱是否只包含abcd:'+ goodsName.containsOnly('abcd'));
            
 /*
    public Boolean containsWhitespace()
    //譯:判斷字符串是否包含空格,包含返回true,不包含返回false
 */
 System.debug('商品名稱是否包含空格 : ' + goodsName.containsWhitespace());
            
 /*
    public Integer countMatches(String substring)
    //譯:判斷子字符串在字符串中出現的次數
 */
 System.debug('商品名稱出現abcd的次數:' + goodsName.countMatches('abcd'));
            
 /*
    public String deleteWhitespace()
    //譯:移除字符串中所有的空格
 */
 String removeWhitespaceString = ' a b c d ';
 System.debug('原  a b c d ,移除空格的字符串顯示爲:' + removeWhitespaceString.deleteWhitespace());
            
 /*
    public String difference(String anotherString)
    //譯:返回兩個字符串之間不同,如果anotherString爲空字符串,則返回空字符串,如果anotherString爲null,則拋異常
    //比較結果以anotherString爲基準,從第一個字符比較,不相同則返回anotherString與源字符串不同之處
 */
    //返回值:bcd啦啦啦
 System.debug('商品名稱和abcd啦啦啦的不同返回值爲:' + goodsName.difference('bcd啦啦啦'));
            
 /*
    public Boolean endsWith(String substring)
    //譯:判斷字符串是否已substring截止,如果是返回true,否則返回false
 */
 System.debug('商品名稱是否已  顯示 截止 :' + goodsName.endsWith('顯示'));
         
 /*
     public Boolean endsWithIgnoreCase(String substring)
     //譯:判斷字符串是否已substring截止(不區分大小寫),如果是返回true,否則返回false
 */
 System.debug('商品名稱是否已  顯示 截止(不區分大小寫) :' + goodsName.endsWithIgnoreCase('顯示'));
            
 /*
    public Boolean equals(Object anotherString)
    //譯:判斷字符串是否和其他字符串相同
 */
            
 /*
    public Boolean equalsIgnoreCase(String anotherString)
    //譯:判斷字符串是否和其他字符串相同(不區分大小寫)
 */
            
 String testEquals = 'AbCd123漢字顯示';
         
 System.debug('商品名稱是否和testEquals字符串相同:' + goodsName.equals(testEquals));
            
 System.debug('商品名稱是否和testEquals字符串相同:(不區分大小寫)'+goodsName.equalsIgnoreCase(testEquals));
            
 /*
    public static String format(String stringToFormat, List<String> formattingArguments)
    //譯:將轉換的參數替換成相同方式的字符串中
 */
 String sourceString = 'Hello {0} ,{1} is good';
 List<String> formattingArguments = new String[]{'Zero','Apex'};
 System.debug('替換sourceString內容以後顯示爲:' + String.format(sourceString,formattingArguments));
            
 /*
    public static String fromCharArray(List<Integer> charArray)
    //譯:將char類型數組轉換成String類型
 */
 List<Integer> charArray = new Integer[] {55,57};
 String destinatioin = String.fromCharArray(charArray);
 System.debug('通過fromCharArray方法轉換的字符串爲:' + destinatioin);
     
            
 /*
    public List<Integer> getChars()
    //譯:返回字符串的字符列表
 */
 List<Integer> goodsNameChars = goodsName.getChars();
            
 /*
    public static String getCommonPrefix(List<String> strings)
    //譯:獲取列表共有前綴
 */
 List<String> strings = new String[]{'abcdf','abe'};
 String commonString = String.getCommonPrefix(strings);
 System.debug('共有前綴:' + commonString);
            
 //goodsName.getLevenshteinDistance();//待學習
            
 /*
    public Integer hashCode()
    //譯:返回字符串的哈希值
 */
 Integer hashCode = goodsName.hashCode();
 System.debug('商品名稱的哈希值爲:'+hashCode);
 /*
    public Integer indexOf(String substring)
    //譯:返回substring第一次在字符串中出現的位置,如果不存在返回-1
 */
 System.debug('cd 在商品名稱中出現的位置:' + goodsName.indexOf('cd'));
            
 /*
    public Integer indexOf(String substring,Integer index)
    //譯:返回substring第一次在字符串中出現的位置,起始查詢字符串的位置爲index處
 */
 System.debug('cd 在商品名稱中出現的位置:' + goodsName.indexOf('cd',2));
            
 /*
    public Integer indexOfAny(String substring)
    //譯:substring任意一個字符第一次在字符串中出現的位置
 */
 System.debug('商品信息中select任意字符最先出現位置:' + goodsName.indexOfAny('select'));
            
 /*
    public Integer indexOfAnyBut(String substring)
    //譯:返回substring任意一個字符不被包含的第一個位置,無則返回-1
 */
 System.debug('商品信息中select任意一個字符最先不被包含的位置'+goodsName.indexOfAnyBut('select'));
            
 /*
    public Integer indexOfChar(int char)
    //譯:返回字符串中char字符最先出現的位置
 */
 Integer firstChar = goodsName.indexOfChar(55);
            
 /*
    public Integer indexOfDifference(String compareTo)
    //譯:返回兩個字符串第一個不同位置的座標
 */
 System.debug('商品名稱與abce字符串第一個不同的位置爲:' + goodsName.indexOfDifference('abce'));
            
 /*
    public Integer indexOfIgnoreCase(String substring)
    //譯:返回substring在字符串中第一個出現的位置(不考慮大小寫)
 */
 System.debug('商品名稱中第一個出現CD位置的爲(不分大小寫)' + goodsName.indexOfIgnoreCase('CD'));
            
 /*
    public Boolean isAllLowerCase()
    //譯:字符串是否均爲小寫,如果是返回true,否則返回false
 */
 System.debug('商品名稱中是否全是小寫: ' + goodsName.isAllLowerCase());
            
 /*
    public Boolean isAllUpperCase()
    //譯:字符串是否均爲大寫,如果是返回true,否則返回false
 */
 System.debug('商品名稱中是否全是大寫:' + goodsName.isAllUpperCase());
            
 /*
    public Boolean isAlpha()
    //譯:如果當前所有字符均爲Unicode編碼,則返回true,否則返回false
 */
 System.debug('商品名稱是否均爲Unicode編碼:' + goodsName.isAlpha());
            
 /*
    public Boolean isAlphanumeric()
    //譯:如果當前所有字符均爲Unicode編碼或者Number類型編碼,則返回true,否則返回false
 */
 System.debug('商品名稱是否均爲Unicode或者Number類型編碼:' + goodsName.isAlphanumeric());
            
 /*
    public Boolean isAlphanumericSpace()
    //譯:如果當前所有字符均爲Unicode編碼或者Number類型或者空格,則返回true,否則返回false
 */
 System.debug('商品名稱是否均爲Unicode,Number或者空格' + goodsName.isAlphanumericSpace());
            
 /*
    public Boolean isAlphaSpace()
    //譯:如果當前所有字符均爲Unicode或者空格,則返回true,否則返回false
 */
 System.debug('商品名稱是否均爲Unicode,或者空格' +goodsName.isAlphaSpace());
            
 /*
    public Boolean isAsciiPrintable()
    //譯:如果當前所有字符均爲可打印的Asc碼,則返回true,否則返回false
 */
 System.debug('商品名稱所有字符是否均爲可打印的Asc碼:' + goodsName.isAsciiPrintable());
            
 /*
    public Boolean isNumeric()
    //譯:如果當前字符串只包含Unicode的位數,則返回true,否則返回false
 */
 System.debug('商品名稱所有字符是否均爲Unicode的位數:' + goodsName.isNumeric());
            
 /*
    public Boolean isWhitespace()
    //譯:如果當前字符只包括空字符或者空,則返回true,否則返回false
 */
 System.debug('商品名稱所有字符只包括空字符或者空:' + goodsName.isWhitespace());
            
  /*
    public static String join(Object iterableObj, String separator)
    //譯:通過separator連接對象,通用於數組,列表等
 */
 List<Integer> intLists = new Integer[] {1,2,3};
 String s = String.join(intLists,'/');//s = 1/2/3
            
            
 /*
    public Boolean lastIndexOf(String substring)
    //譯:substring在字符串中最後出現的位置,不存在則返回-1
 */
 System.debug('cd最後一次出現的位置:' + goodsName.lastIndexOf('cd'));
 /*
    public Boolean lastIndexOfIgnoreCase(String substring)
    //譯:substring在字符串中最後出現的位置(忽略大小寫),不存在則返回-1
 */
 System.debug('Cd最後一次出現的位置(不考慮大小寫):' + goodsName.lastIndexOfIgnoreCase('Cd'));
            
 /*
    public String left(Integer index)
    //譯:獲取從零開始到index處的字符串
                
 */
 System.debug('商品名稱前三個字符 : abc' + goodsName.left(3));
            
 /*
     public String leftPad(Integer length)
     //譯:返回當前字符串填充的空間左邊和指定的長度
 */
 String s1 = 'ab';
 String s2 = s1.leftPad(4);//s2 = '  ab';
 /*
    public Integer length()
    //譯:返回字符串長度
 */
 System.debug('商品名稱長度:' + goodsName.length());
 /*
    public String mid(Integer startIndex,Integer length);
    //譯:返回新的字符串,第一個參數爲起始位,第二個字符爲字符的長度//類似於substring
 */
 System.debug('商品名稱截取字符串' + goodsName.mid(2,3));
            
 /*
    public String normalizeSpace()
    //譯:前後刪除空白字符
 */
 String testNormalizeSpace = 'abc\t\n  de';
 System.debug('通過normalizeSpace處理後的字符串爲:' + testNormalizeSpace.normalizeSpace());
            
 /*
    public String remove(String substring)
    //譯:移除所有特定的子字符串,並返回新字符串
    public String removeIgnorecase(String substring)
    //譯:移除所有特定的子字符串(忽略大小寫),並返回新字符串
 */
 System.debug('商品名稱移除12後的字符串爲:' + goodsName.remove('12'));
            
 /*
    public String removeEnd(String substring)
    //譯:當且僅當子字符串在後面移除子字符串
 */
 System.debug('當顯示在商品名稱最後時移除:' + goodsName.removeEnd('顯示'));
            
 /*
    public String removeStatrt(String substring)
    //譯:當且僅當子字符串在後面移除子字符串
 */
 System.debug('當ab在商品名稱最前面時移除' + goodsName.removeStart('ab'));
            
 /*
    public String repeat(Integer numberOfTimes)
    //譯:重複字符串numberOfTimes次數
 */
 System.debug('重複商品名稱兩次的顯示爲:' + goodsName.repeat(2));
            
 /*
    public String repeat(String separator, Integer numberOfTimes)
    //譯:重複字符串numberOfTimes次,通過separator作爲分隔符
 */
 System.debug('通過separator分隔符重複字符串兩次:' + goodsName.repeat('-',2));
            
 /*
    public String replace(String target, String replacement)
    //譯:將字符串中的target轉換成replacement
 */
 System.debug('將商品名稱中ab替換成AB' + goodsName.replace('ab','AB'));
            
 /*
    public String replaceAll(String target,String replacement)
 */
 System.debug('將商品名稱中ab全部替換成AB' + goodsName.replaceAll('ab','AB'));
            
 /*
    public String reverse()
    //譯:字符串倒序排列
 */
 System.debug('商品名稱倒序:' + goodsName.reverse());
            
 /*
    public String right(Integer length)
    //譯:從右查詢返回length的個數的字符串
 */
 System.debug('返回商品名稱後三位字符:' + goodsName.right(3));
            
 /*
    public String[] split(String regExp)
    //譯:通過regExp作爲分隔符將字符串分割成數組
 */
 String[] sonSplitString = goodsName.split('1');//通過1分割字符串
            
 /*
    public String[] split(String regExp, Integer limit)
    //譯:通過regExp作爲分隔符將字符串分割成數組,limit顯示數組個數
 */
 String [] sonSplitString1 = goodsName.split('1',2);
            
 /*
    public Boolean startsWith(string substring)
    //譯:判斷字符串是否以substring開頭,如果是返回true,不是返回false
 */
 System.debug('商品名稱是否以abcd開始:' + goodsName.startsWith('abcd'));
            
 /*
    public String substring(Integer length)
    //譯:截取字符串固定長度
 */
 System.debug('截取商品名稱前四個字符: ' + goodsName.substring(4));
            
 /*
    public String toLowerCase()
    //譯:將字符串轉換成小寫
 */
 System.debug('商品名稱轉換成小寫:' + goodsName.toLowerCase());
            
 /*
    public String toUpperCase()
    //譯:將字符串轉換成大寫
 */
 System.debug('商品名稱轉換成大寫:' + goodsName.toUpperCase());
                    
 /*
    public String trim()
    //譯:去字符串左右空格
 */
 System.debug('去空格後商品名稱:' + goodsName.trim());
         
 /*
    public String uncapitalize()
    //譯:將字符串第一個轉換成小寫
 */
         System.debug('商品名稱第一個單詞轉換成小寫:' + goodsName.uncapitalize());
         
 /*
    public static String valueOf(Object objectToConvert)
    //譯:將Object類型轉換成String類型,其中Object類型包括以下:
    // Date,DateTime,Decimal,Double,Integer,Long,Object
 */
 System.debug('將Double類型轉換成String類型' + String.valueOf(3.45));

                7. Boolean

Boolean 類型聲明一個布爾類型,和Java的區別爲 : 

Boolean類型變量有三個取值:true,false,null(default),所以使用Boolean類型聲明的時候必須賦予初始值,否則初始值爲null

二.時間日期類型

        1.Datetime

 Datetime 類型聲明一個日期時間的對象,包含兩部分 : 日期 , 時間 . 因爲salesforce一般製作global項目,所以日期時間一般取格林時間.Datetime無構造函數,如果實例化只能通過靜態方法初始化.

以下爲Datetime的部分主要方法 :

 Datetime nowDatetime = Datetime.now();
  Datetime datetime1 = Datetime.newInstance(2015,3,1,13,26,0);
  String datetimeString = '2016-3-1 PM14:38';
  /*
     Datetime datetime2 = Datetime.parse(datetimeString);
     Datetime datetime3 = Datetime.valueOf(datetimeString);
  */
  System.debug('通過初始化年月日時分秒得到的Datetime,並轉換格式值:'+datetime1.format('yyyy-MM-dd HH:mm:ss'));
  System.debug('當前日期時間:' + nowDatetime.format());
  /*
     System.debug('通過parse方法初始化的datetime:' + datetime2.format());
     System.debug('通過valueOf方法初始化的datetime'+datetime3.format());
  */
  datetime1 = datetime1.addDays(1);
  datetime1 = datetime1.addMonths(1);
  datetime1 = datetime1.addYears(1);
  datetime1 = datetime1.addHours(1);
  datetime1 = datetime1.addMinutes(1);
  datetime1 = datetime1.addSeconds(1);
  System.debug('更改後的日期時間:' + datetime1.format('yyyy-MM-dd HH:mm:ss'));
  Date date1 = datetime1.date();
  System.debug('datetime1對應的Date爲:'+date1.format());
             
  Date dateGmt = datetime1.dateGmt();
  System.debug('datetime1對應的DateGmt值爲:'+dateGmt.format());
  Integer year = datetime1.year();
  Integer yearGmt = datetime1.yearGmt();
  Integer month = datetime1.month();
  Integer monthGmt = datetime1.monthGmt();
  Integer day = datetime1.day();
  Integer dayGmt = datetime1.dayGmt();
  Integer dayOfYear = datetime1.dayOfYear();
  Integer dayOfYearGmt = datetime1.dayOfYearGmt();
  Integer hour = datetime1.hour();
  Integer hourGmt = datetime1.hourGmt();
  Integer minute = datetime1.minute();
  Integer minuteGmt = datetime1.minuteGmt();
  Integer second = datetime1.second();
  Integer secondGmt = datetime1.secondGmt();
  System.debug('year : '+ year + '\tyearGmt : ' + yearGmt);
  System.debug('month : ' + month + '\tmonthGmt : '+ monthGmt);
  System.debug('day : ' + day + '\tdayGmt : ' + dayGmt);
  System.debug('hour : ' + hour + '\thourGmt : ' + hourGmt);//兩者不同 一個爲14 Gmt爲6
  System.debug('minute : ' + minute + '\tminuteGmt : ' + minuteGmt);
  System.debug('second : ' + second + '\tsecondGmt : ' + secondGmt);
  System.debug('dayOfYear : ' + dayOfYear + '\tdayOfYearGmt : ' + dayOfYearGmt);
  System.debug('轉成本地日期並以長日期類型顯示:'+ datetime1.formatLong());
  Long timeL = datetime1.getTime();
  System.debug('轉成time類型的Long類型顯示爲:'+timeL.format());
  Datetime datetime5 = Datetime.newInstance(2016,4,2);
  System.debug('datetime1與datetime2是否同一天:' + datetime1.isSameDay(datetime5));//true

        2.Date

Date類型聲明一個日期的對象,Date可以和Datetime相互轉換,主要需要掌握二者關係以及相互轉換。

Date date2 = Date.today();
System.debug('當前日期:' + date2.format());
Date date3 = Date.newInstance(2016,3,1);
String dateString = '2016-3-1';
Date date4 = Date.parse(dateString);
Date date5 = Date.valueOf(dateString);
System.debug('通過newInstance實例化:' + date3.format());
System.debug('通過parse實例化:' + date4.format());
System.debug('通過valueOf實例化:' + date5.format());

date3 = date3.addMonths(1);
date3 = date3.addDays(1);
System.debug('date3的日期爲:' + date3.format());
Integer year1 = date3.year();
Integer month1 = date3.month();
Integer day1 = date3.day();
System.debug('year : ' + year1);
System.debug('month : ' + month1);
System.debug('day : ' + day1);
Integer dayOfYear1 = date3.dayOfYear();
System.debug('dayOfYear : ' + dayOfYear1);


Integer daysBetween = date3.daysBetween(date4);//date4-date3
System.debug('date3和date4相差天數:' + daysBetween);

System.debug('date4和date5是否相同日期:'+date4.isSameDay(date5));

System.debug('date3和date4相差月數:' + date3.monthsBetween(date4));

System.debug('調用toStartOfMonth執行值:' + date3.toStartOfMonth().format());//返回本月第一天
/*
    public Date toStartOfWeek()
    //譯:返回本月第一個週日,如果本月1日非週日,則返回上月最晚的週日
*/
System.debug('調用toStartOfWeek執行值: ' + date3.toStartOfWeek().format());

            3.time

Time類型聲明一個時間的對象,對於時間需要考慮的是:因爲中國時間和格林時間相差8小時,所以具體項目時如果是global項目需要考慮使用格林時間,即GMT時間。

三 . 集合類型 

集合主要有 三種 類型 : List , Set ,Map. 

        1.List

List代表一類的有序數據列表。數據序號從0開始。與JAVA不同的是:List是一個類,並且不存在ArrayList等子類 ,如ArrayList,LinkedList等

List可以通過自身構造函數實例化,也可以通過數組進行實例化.

以下爲List主要方法 :

//Initialize the List
List ListOfStatesMethod = new List();

//This statement would give null as output in Debug logs
System.debug('Value of List'+ ListOfStatesMethod);


//Add element to the list using add method
ListOfStatesMethod.add('New York');
ListOfStatesMethod.add('Ohio');


//This statement would give New York and Ohio as output in Debug logs
System.debug('Value of List with new States'+ ListOfStatesMethod);


//Get the element at the index 0
String StateAtFirstPosition = ListOfStatesMethod.get(0);


//This statement would give New York as output in Debug log
System.debug('Value of List at First Position'+ StateAtFirstPosition);


//set the element at 1 position
ListOfStatesMethod.set(0, 'LA');


//This statement would give output in Debug log
System.debug('Value of List with element set at First Position'+ ListOfStatesMethod[0]);


//Remove all the elements in List
ListOfStatesMethod.clear();


//This statement would give output in Debug log
System.debug('Value of List'+ ListOfStatesMethod);

            2.Set

Set代表一類數據的無序列表。與JAVA不同的是:Set是一個類,不存在HashSet等子類。

以下爲Set主要方法 :

//Adds an element to the set
//Define set if not defined previously
Set ProductSet = new Set{'Phenol', 'Benzene', 'H2SO4'};
ProductSet.add('HCL');
System.debug('Set with New Value '+ProductSet);

//Removes an element from set
ProductSet.remove('HCL');
System.debug('Set with removed value  '+ProductSet);


//Check whether set contains the particular element or not and returns true or false
ProductSet.contains('HCL');
System.debug('Value of Set with all values '+ProductSet);

            3.Map

Map代表着鍵值對,與JAVA用法類似,區別爲Map是一個類,不是接口,不存在HashMap<K,V>等子類

以下爲Map的主要方法 :

// Define a new map
Map ProductCodeToProductName = new Map(); 

// Insert a new key-value pair in the map where '1002' is key and 'Acetone' is value
ProductCodeToProductName.put('1002', 'Acetone');


// Insert a new key-value pair in the map where '1003' is key and 'Ketone' is value 
ProductCodeToProductName.put('1003', 'Ketone'); 


// Assert that the map contains a specified key and respective value
System.assert(ProductCodeToProductName.containsKey('1002')); 
System.debug('If output is true then Map contains the key and output is :'+ProductCodeToProductName.containsKey('1002'));


// Retrieves a value, given a particular key
String value = ProductCodeToProductName.get('1002'); 
System.debug('Value at the Specified key using get function: '+value);


// Return a set that contains all of the keys in the map
Set SetOfKeys = ProductCodeToProductName.keySet(); 
System.debug('Value of Set with Keys '+SetOfKeys);

四 . 流程控制語句

運算與控制語句和JAVA基本類似

詳細瞭解這些基本類型變量,集合以及相關方法請查看商法API的鏈接。其實掌握一些主要的方法就可以,其他方法不用掌握大概清楚實現功能就好,具體需要的時候查看API看一下用法就可以。

給小夥伴們附個鏈接 : 

沒有代碼基礎,怎麼學Salesforce開發?(附Apex學習資源)

(^_^)~喵~!!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章