→[[Java関連]]
→Javaのリフレクション
→Eclipse関連
→JavaのWebアプリ開発
#contents
*Tips集Webサイト [#t58aeb52]
-[[裏Javaメモ>http://www.ne.jp/asahi/hishidama/home/tech/java/strange.html]]
--Javaの微妙なネタ
-[[Java(SE) API逆引き辞典>http://always-pg.com/java/j2se_rd/]]
-[[Javaのとても小さい小技メモ>http://kamakura.cool.ne.jp/oppama/jaco/index.html]]
-[[Java 逆引きリファレンス>http://www.stackasterisk.jp/tech/javaClassref/index.jsp]]
-[[Java Tips index@IT>http://www.atmarkit.co.jp/fjava/javatips/index.html]]
-[[Java Tips集>http://www.masatom.in/pukiwiki/Java/TIPS%BD%B8/]]
*文法系Tips [#lcf79da5]
-[[あまり知られていないと思われる Java のインスタンスイニシャライザの紹介>https://satosystems.hatenablog.com/entry/20120905/1346805620]] 2012
-[[【Java】匿名クラス>https://nompor.com/2017/11/08/post-903/]]
--匿名クラスはコンストラクタでの初期化処理ができません。
--インスタンス化した直後であれば、匿名クラス本体のインスタンスなので、自前で定義したメソッドを呼び出せます。
--もし、匿名クラスで初期化処理をしたい場合は、この性質を利用するか、インスタンスイニシャライザを使用する方法が候補に挙がります。
-[[Local Variable Type Inference: Style Guidelinesを読んだ>https://kagamihoge.hatenablog.com/entry/2019/11/13/163855]] 2019.11
-[[弱い参照とな>http://qiita.com/yyyske/items/daa5c844647604e27e4f]] 2014.8
-[[戻り値が NotNull であることをアノテーションで表現できますか?>https://ja.stackoverflow.com/questions/1880/%E6%88%BB%E3%82%8A%E5%80%A4%E3%81%8C-notnull-%E3%81%A7%E3%81%82%E3%82%8B%E3%81%93%E3%81%A8%E3%82%92%E3%82%A2%E3%83%8E%E3%83%86%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%A7%E8%A1%A8%E7%8F%BE%E3%81%A7%E3%81%8D%E3%81%BE%E3%81%99%E3%81%8B]]
--@NonNull
--JSR-305 を導入する
-[[privateなコンストラクタのクラスについて>http://java-etc.cocolog-nifty.com/blog/2006/11/private_d99b.html]]
-[[インタフェースのキャスト>http://www.kab-studio.biz/Programing/OOPinJava/10/03.html]]
-[[ラベル付きステートメント>http://www.hcn.zaq.ne.jp/no-ji/reseach/20021120.html]]
** ストリームAPI [#f28070a3]
-[[Java8 stream APIサンプルコード>https://qiita.com/rubytomato@github/items/93011c75ee4af6b59452]]
-[[Javaでリストの集約(Collectors.groupingBy)>https://qiita.com/KevinFQ/items/c4e7b5835487180d9659]] 2020.9
** Optional型 [#mf9b4c34]
-[[クラス java.util.Optionalのおさらいメモ>https://qiita.com/rubytomato@github/items/92ac7944c830e54aa03d]] 2020.5
-[[`get()`を使うな 〜 敗北者の Optional>https://qiita.com/BlueRayi/items/ef46496ef2ef36b9cbb7]] 2020.3
**例外処理 [#f7477992]
-[[Java のチェック例外と非チェック例外の考察まとめ>http://d.hatena.ne.jp/ebc_2in2crc/20120729/1343557350]] 2012.7.29
-[[Javaのチェック例外と非チェック例外について>http://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q1126696326]]
**ラムダ式 [#u0e57c9f]
-[[徹底解説! Javaのラムダ式はどういうもので、どう使えばいいのか!>https://engineer-club.jp/java-lambda-expression]] 2020.9
-[[Java 8: Preferred way to count iterations of a lambda?>https://stackoverrun.com/ja/q/7909293]] 2020.9
--ラムダ式の中で外のカウンタを使うには?
-[[Java 8のStream処理はここまで省略できる!>http://qiita.com/munieru/items/6c0dbada463e00429fd1]] 2017.8.19
**static初期化子とインスタンス初期化子 [#a3085659]
-http://www.genzou.sakura.ne.jp/class/inisharaiza_shokikasi.html
// static初期化子の例
public class MyTest {
static int[] hoge;
static {
hoge = new int[5];
for( int i = 0; i < 5; i++ ){
hoge[i] = i;
}
}
public static void main(String[] args){
for( int i = 0; i <hoge.length; i++) {
System.out.print(MyTest.hoge[i] + ",");
}
}
}
// インスタンス初期化子の例
public class MyTest {
static int[] hoge;
{
hoge = new int[5];
for( int i = 0; i < 5; i++ ){
hoge[i] = i;
}
}
public static void main(String[] args){
try {
MyTest m = new MyTest(); // インスタンス初期化子にはこれが必要
for( int i = 0; i <hoge.length; i++) {
System.out.print(MyTest.hoge[i] + ",");
}
} catch( Exception e ) {
System.out.print("例外発生:" + e.toString() );
e.printStackTrace();
}
}
}
-ArrayListを定義すると同時に初期化するサンプル
ArrayList<HogeEnum> list = new ArrayList<HogeEnum>() {
{ add(HogeEnum.A); }
{ add(HogeEnum.B); }
{ add(HogeEnum.C); }
};
**可変個引数の例 [#y02b00ee]
int sum(Integer... values){
int sum = 0;
for(int val : values){
sum += val;
}
return sum;
}
//呼び出し側
int sum = sum(1,2,3,4,5);
* JavaのSerializableを実際にアプリケーションを動かしながら理解する [#qfbd3fb6]
-[[JavaのSerializableを実際にアプリケーションを動かしながら理解する>https://qiita.com/taumax/items/1559439efe0607595465]] 2020.7
*util.Objects [#g06e922b]
-[[クラス java.util.Objectsのおさらいメモ>https://qiita.com/rubytomato@github/items/ba38877ed5a00dd24f16]] 2020.5
*ジェネリクス関連 [#b61b01f2]
-[[Javaジェネリクス再入門>http://d.hatena.ne.jp/Nagise/20101105/1288938415?sid=201781F]] 2010.11.5
-[[Java変態文法最速マスター>http://d.hatena.ne.jp/Nagise/20100202/1265131791]]
-[[Javaのジェネリクスで,T.class や new T() ができず悩んだ話 (型パラメータのインスタンス化に関し、フレームワーク設計からケーススタディ)>http://d.hatena.ne.jp/language_and_engineering/20120502/p1]] 2012.5
**Genericsのワイルドカードを使いこなす [#h750be49]
-http://www.ibm.com/developerworks/jp/java/library/j-jtp04298.html
-http://www.ibm.com/developerworks/jp/java/library/j-jtp07018.html
**リストを渡してリストを返すようなメソッドでジェネリックを使ってキャストしなくてもいいようにする [#r8651a78]
public <T> List<T> hoge( List<T> list)
-http://www.eeb.co.jp/2007/11/_25.html
--戻り値であるList<T>の前に、<T>という型変数が宣言されていることに注目してください。このように書くことにより、メソッド宣言時に具体的な要素の型を指定せずにメソッドが宣言できるのです。
--型変数を<T extends Number>のように書くことも可能で、そのときの動作は容易に想像できるかと思います。
*日付/時刻処理いろいろ [#wa075aaa]
-[[Javaバージョン別の改元(新元号)対応まとめ>https://qiita.com/yamadamn/items/56e7370bae2ceaec55d5]] 2019.1
-Timestamp型からDateを経由してCalendarを作る
java.util.Date = new java.util.Date(ts.getTime());
Calendar now = Calendar.getInstance();
now.setTime(date);
-ISO8601形式の日付をDate型に変換して返す [#r37f066f]
public static Date Iso8601toDate(String isoDate)
throws java.text.ParseException{
try {
Calendar cal =DatatypeConverter.parseDateTime(isoDate);
return cal.getTime();
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
-カレント月(YYYYMM)取得
java.util.Date dtNow = new java.util.Date();
SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMM");
String ymNow = formatter.format(dtNow);
-1月進めて月を取得
Date dt = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.add(Calendar.MONTH, 1);
dt = calendar.getTime();
SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMM");
String ymNow = formatter.format(dt);
*Cで言うmemsetに当たる処理 [#r78bdfb5]
import java.util.*;
:
byte[] buf = new byte[200];
Arrays.fill(buf,0x20);
*Runtime#addShutdownHookで JVM 終了時に処理を実行する [#g1cf1f8e]
-http://www.smallstyle.com/20070215.html
*Velocity [#nca80fcf]
-[[汎用テンプレートエンジンVelocity>http://www.stackasterisk.jp/tech/java/velocity01_01.jsp]]
--http://velocity.apache.org/
*マルチスレッド [#z0afd4c1]
-[[マルチスレッドプログラミングの入門>http://programming-10000.hatenadiary.jp/entry/20140530/1401450268]] 2014.5.30
-チュートリアル
--http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html
*Eclipseからアプリを実行して、OutOfMemoryErrorが出たでござる [#b7856232]
-http://d.hatena.ne.jp/dkfj/20090626/1245983960
-実行->Javaアプリケーションをする前に、Open実行Dialogで設定画面を開きArguments VM arguments:で、-Xmx256mといった感じで適当なサイズのメモリを割り当てれば問題解決です。
*強制ガベージコレクション [#m2465ffe]
-System.gc() もしくは Runtime.getRuntime().gc()
*テキストファイルの読み込み [#l0820c18]
-http://www.tohoho-web.com/java/file.htm
import java.io.*;
class BufferedReaderTest {
public static void main(String[] args) {
try {
FileReader in = new FileReader("file.txt");
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
* イメージをpngファイルに出力 [#ua836eae]
/**
* pngファイルに出力
* @param im 出力したいイメージ
* @param fname 出力ファイル名
* @throws FileNotFoundException
* @throws IOException
*/
public static void savePng(BufferedImage im, String fname)
throws FileNotFoundException, IOException {
// Open output file.
OutputStream out = new FileOutputStream(fname);
ImageOutputStream ios =
ImageIO.createImageOutputStream(out);
ImageWriter iw = (ImageWriter)ImageIO.
getImageWritersByFormatName("png").next();
iw.setOutput(ios);
iw.write(im);
// Close output file.
out.close();
}
*イメージ⇔バイト列の変換 [#hb7b4c52]
/**
* イメージをバイト列に変換する
* @param im イメージ
* @param formatName フォーマット名 png, bmp, jpeg など
* @return バイト列
* @throws IOException
*/
public static byte[] getBytesFromImage(BufferedImage im, String formatName)
throws IOException{
if(formatName == null)
formatName = "png";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(im, formatName, bos);
return bos.toByteArray();
}
/**
* バイト列からイメージを作成する
* @param bytes
* @return イメージ
* @throws IOException
*/
public static BufferedImage getImageFromBytes(byte[] bytes)
throws IOException{
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
BufferedImage im = ImageIO.read(bis);
return im;
}
*フォントにアンチエイリアスをかける [#f73a05c7]
-参考ページ:http://itpro.nikkeibp.co.jp/article/COLUMN/20070205/260649/
private void testDrawAnti(Graphics2D g) {
String text = "Limousine";
// HRGB
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
g.drawString("HRGB:" + text, 10, 140);
// HBGR
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR);
g.drawString("HBGR:" + text, 10, 180);
// VRGB
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB);
g.drawString("VRGB:" + text, 10, 220);
// VBGR
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR);
g.drawString("VBGR:" + text, 10, 260);
}
*BigDecimalの丸め方 [#p8673458]
-http://always-pg.com/java/j2se_rd/number/setscale.html
* 指定のバイト長さになるようにスペースを詰める [#ba6ea65c]
* @param s 対象の文字列
* @param length つめた結果の長さ(バイト長)
* @param leftPad trueなら左に詰める(文字は右詰になる)
* @return 詰めた文字列
* @throws UnsupportedEncodingException
*/
public static String padSpaceHankaku(String s, int length, booleanleftPad)
throwsUnsupportedEncodingException{
if(isEmpty(s)){
return repeatChar(' ', length);
}
else {
//シフトJISでバイトにしたときの長さを得て、足りない分を補う
byte[] bytes = s.getBytes("SJIS");
int spaceLen = length - bytes.length;
if(spaceLen <= 0)
return s;
else {
if(leftPad)
return repeatChar(' ',spaceLen) + s;
else
return s + repeatChar(' ',spaceLen);
}
}
}
*バイト列の16進文字列化 [#tfd6e3a0]
private String toHex(byte buffer[]) {
StringBuffer sb = new StringBuffer(buffer.length * 2);
for (int i = 0; i < buffer.length; i++) {
sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
}
return sb.toString();
}
*jar内のクラスファイルの一覧を得るバッチファイル [#kceae917]
-http://cjasmin.fc2web.com/tips/search_class.html
*前ゼロつける [#h1d74b71]
-文字列に前ゼロ:素朴なやり方
private String padLeadingZero(String value, int width) {
String wrkValue = value;
if(wrkValue != null){
if(wrkValue.length() < width) {
StringBuffer sb = new StringBuffer();
int zeroLen = width - wrkValue.length();
for( int i = 0; i < zeroLen ; i++) {
sb.append("0");
}
wrkValue = sb.append(wrkValue).toString();
}
}
return wrkValue;
}
-左側にn桁のゼロ文字列をつけた上で右n桁のsubstringを使う方法もある
-数値に前ゼロ
String.format("%07d", n)
または
DecimalFormat df = new DecimalFormat();
df.applyPattern("0000000");
String max_str = df.format(n);
*ファイル一覧取得 [#fa0747de]
-http://sattontanabe.blog86.fc2.com/blog-entry-56.html
*Java のスタンドアロンプログラムで終了コードを設定するには [#td9a655b]
System.exit(-1);
*PDFを生成する [#tc59c185]
-http://www.atmarkit.co.jp/fjava/javatips/121jspservlet41.html
*XMLに対応したProperties [#z37787f0]
-http://www.javainthebox.net/laboratory/J2SE1.5/TinyTips/Properties/Properties.html
*プロパティファイル読み込み [#zea80fc5]
-下のようにgetPath()でパスを取得する方法ではjarファイルにしたときFileNotFoundになる。jarファイルになっても読めるやり方は
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource("config.properties");
prop.load(url.openStream());
-参考:[[jarファイルをエクスポートしたときファイルを開けなくなる>http://d.hatena.ne.jp/g-wong/20080710/1215695631]]
-リソースフォルダにあるプロパティファイルを読み込む
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource("config.properties");
//パスにスペースなどがあるとURLエンコードされる点に注意
String path = url.getPath();
String path2 = URLDecoder.decode(path, "UTF-16");
prop.load(new FileInputStream(path2));
-http://d.hatena.ne.jp/mikeda/20090325/1238017508
String configFile = "prop.conf";
Properties prop = new Properties();
try {
prop.load(new FileInputStream(configFile));
} catch (IOException e) {
e.printStackTrace();
return;
}
String name = prop.getProperty("name");
String addr = prop.getProperty("addr");
*スタンドアロンアプリで二重起動防止 [#qd1f8983]
-ファイルのロックを使う
-http://oshiete1.goo.ne.jp/qa2030088.html
import java.io.File;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class Sample {
public static void main(String[] args) {
//起動チェック
final FileOutputStream fos = new FileOutputStream(new File("lock"));
final FileChannel fc = fos.getChannel();
final FileLock lock = fc.tryLock();
if (lock == null) {
//既に起動されているので終了する
return;
}
//ロック開放処理を登録
Runtime.getRuntime().addShutdownHook(
new Thread() {
public void run() {
if (lock != null && lock.isValid()) {
lock.release();
}
fc.close();
fos.close();
}
}
);
//処理を続行
}
}
*ImageI/O関連 [#fc0337dc]
-[[ImageI/O APIガイド>http://sdc.sun.co.jp/java/docs/j2se/1.4/ja/docs/ja/guide/imageio/index.html]]
--http://sdc.sun.co.jp/java/docs/j2se/1.4/ja/docs/ja/guide/imageio/spec/imageio_guideTOC.fm.html
-[[ImageI/O 説明>http://www.javainthebox.net/laboratory/JDK1.4/Graphics/ImageIO/ImageIO.html]]
-[[ImageI/Oファイルで画像ファイルを読み書きする>http://www.javadrive.jp/java2d/bufferedImage/index2.html]]
-[[Graphics2Dによる描画>http://codezine.jp/article/detail/1021?p=1]]
**Graphics2D+ImageI/Oを使って画像に別の画像を挿入したファイルを作成する [#k86aad8b]
-参考:http://www.javadrive.jp/java2d/bufferedImage/index2.html
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.awt.*;
import java.awt.geom.*;
import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;
static void outByImageIO() throws Exception{
// イメージの作成
// BufferedImage im = new BufferedImage(600,800,
// BufferedImage.TYPE_INT_RGB);
BufferedImage im = ImageIO.read(new File("sample.png")); //挿入される画像
BufferedImage im2 = ImageIO.read(new File("test2.jpg")); //挿入する画像
Graphics2D g = im.createGraphics();
g.drawImage(im2, 20,10, null);
g.dispose();
// Open output file.
OutputStream out = new FileOutputStream("test.jpg");
ImageOutputStream ios =
ImageIO.createImageOutputStream(out);
ImageWriter iw = (ImageWriter)ImageIO.
getImageWritersByFormatName("jpeg").next();
iw.setOutput(ios);
iw.write(im);
// Close output file.
out.close();
}
*正規表現によるマッチング [#t445ef73]
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
public boolean isHogeNumFormat(String arg) {
String regexp = <正規表現の文字列>;
Pattern pat = Pattern.compile(regexp);
return pat.matcher(arg).matches();
}
*シリアルバージョンUIDの生成 [#if425795]
-シリアライズを実装するクラスにはUIDをつける必要がある
-解説:http://www.javaroad.jp/faq/faq_os_eclipse1.htm
-Eclipseではワーニングの出た位置にカーソルを合わせてCtrl+1を押すと生成できる
*実行時の対応ソース行取得 [#o969aba2]
int line = (new Throwable().getStackTrace()[0]).getLineNumber();
*Javaオブジェクトのハッシュコードのルール [#w3ff9fa1]
-The hashCode( ) method is supposed to return an int that should uniquely identify different objects.
-A properly written hashCode( ) method will follow these rules:
--It is repeatable: hashCode(x) must return the same int when called repeatedly, unless set methods have been called.
--It is consistent with equality: if x.equals(y), then x.hashCode( ) must == y.hashCode( ).
--If !x.equals(y), it is not required that x.hashCode( ) != y.hashCode( ), but doing so may improve performance of hash tables; i.e., hashes may call hashCode( ) before equals( ).
-The default hashCode( ) on Sun's JDK returns a machine address, which conforms to Rule 1. Conformance to Rules 2 and 3 depends, in part, upon your equals( ) method. Here is a program that prints the hashcodes of a small handful of objects:
*コンパイラの警告抑制 [#u5033083]
-↓のアノテーションをメソッドにつけるとキャストのときに出る警告を抑制できる
@SuppressWarnings("unchecked")
あまり推奨はできないが…
*バイト配列から文字列への変換 [#g90835e2]
result = new String(bytes, offset, length, charsetName);
-charsetName は "shift-jis"とか
*JNDIのlookupをだましてとりあえず動かす [#bd15b3d3]
public class DummyNamingContext implements InitialContextFactoryBuilder, InitialContextFactory, Context {
public static DummyNamingContext setup() throws Exception {
if (!NamingManager.hasInitialContextFactoryBuilder()) {
final DummyNamingContext instance = new DummyNamingContext();
NamingManager.setInitialContextFactoryBuilder(instance);
return instance;
}
final Context con = NamingManager.getInitialContext(null);
if (con instanceof DummyNamingContext) {
return (DummyNamingContext) con;
}
throw new IllegalStateException("No DummyNamingContext");
}
private final Map<Name, Object> nameMap;
private final Map<String, Object> strMap;
@Override
public void bind(final String name, final Object obj) throws NamingException {
this.strMap.put(name, obj);
}
@Override
public Object lookup(final String name) throws NamingException {
return this.strMap.get(name)
}
...
}
*Javaのソース解析 [#o15fd42f]
-[[JavaParser 使い方メモ>https://qiita.com/opengl-8080/items/50ddee7d635c7baee0ab]] 2017
-[[JDTでJavaのソースコード解析を行う>https://qiita.com/esplo/items/fa93ab6136e7697ed1d9]] 2015
-[[Eclipse JDT AST>http://www.ne.jp/asahi/hishidama/home/tech/eclipse/plugin/develop/jdt/ast.html]]