カスタムラベル
Label.xxx
//xxxはラベル名
カスタム例外
組み込み例外はthrowできないのでカスタム例外を宣言する。
public class MyException extends Exception {}
new MyException('This is bad');
new MyException(e);
new MyException('This is bad', e);
割り算と小数点
Integerを割り算しても答えは0になる。Decimal型で計算する必要がある
Double a = 1/5; //Integerのままでは a=0になる。0.2にはならない
Double a = Double.valueOf(1) / Double.valueOf(5); //a=0.2になる
//小数点第一位で四捨五入する
Double ratio = Decimal.valueOf(ansItems).divide(totalItems, 1, System.RoundingMode.HALF_UP);
//整数値として四捨五入する
ratio = ratio.setScale(0, System.RoundingMode.HALF_UP);
数値を3桁区切りで表示する
Decimal.valueOf(10000).format(); -> 10,000
カスタム設定からの値の取得
階層化しないカスタム設定のケース
public with sharing class xxx_Properties {
private static xxx_Properties__c props {get{
return Ron_Properties__c.getValues('カスタム設定のnameの値');
}}
public static Integer xxxx {get{
return Integer.valueOf(props.get('xxxx__c'));
}}
public static String xxxx {get{
return String.valueOf(props.get('xxxx__c'));
}}
public static String xxxx {
set{
props.put('xxxx__c', value);
}
get{
return (String)props.get('xxxx__c');
}
}
URLエンコード/デコード
型の判定
instanceOfを使用する。
if (abc instanceof String){
...
if (amap instanceof Map<String, String>){
...
try/catch/finally
try {
// Perform some database operations that
// might cause an exception.
} catch(DmlException e) {
// DmlException handling code here.
} catch(Exception e) {
// Generic exception handling code here.
} finally {
// Perform some clean up.
}
テスト実行時に特定のロジックを実行させないようにする
コレクション関連
>Mapからキーの一覧を取得
Set<String> = colorCodes.keySet();
>Mapから値の一覧を取得
List<Object> = colorCodes.values();
>リストが空かどうかのチェック
XXX_c[] xxx = Database.query(soql);
if (xxx.isEmpty()){
....
}
>Listの初期化
String[] entries = new List<String>();
Integer[] nums = new List<Integer>{1, 2, 5, 7};
>List操作
entries.size(); //要素数
entries.add('xx'); //要素を最後に追加
entries.add(0, 'xx'); //要素を先頭(index=0)に追加
entries.addAll(anList); //他のリストを追加
entries.remove(0); //指定されたIndexの要素を削除
>Mapの初期化
Map<String, String> keys = new Map<String, String>();
Map<Integer, String> keys = new Map<Integer, String>{1=>'xxx', 2=>'rew'};
Map<ID, Account> accnts = new Map<Id, Account>([SELECT ID, Name FROM Account]); //sObjectのみ使える。
>Map操作
map.put('key', 'value'); //要素の追加
map.remove('key'); //要素の削除