【Java】for(int i = 0; i < hoge.size(); i++)を卒業しよう!〜For文、拡張For文、Iterator〜
mokabuu
mokabuu.com
先日ひょんなミスから業務中にこのエラーに襲われ
一瞬戸惑ったので今日はこのエラーについて
備忘録も兼ねて何をミスるとこいつが出てくるのか
記事を書こうと思います。
このエラー。
落ち着いて読めば非常にシンプルなものです。
No enclosing instance of type HOGE is accessible.
Must qualify the allocation with an enclosing instance of type HOGE
(e.g. x.new A() where x is an instance of HOGE).
要するに「HOGEにアクセスできねーよ!」ってエラーです。
なのでHOGEにアクセス出来るようにしてあげれば良いのですが
このエラーがどんな時に出るかと言うと次のようなコードを書いてしまった時です。
package com.mokabuu.ri; import java.util.List; import com.mokabuu.dao.BandInfoDao; public class BandInfoRI { public class BandInfoParam { public String bandid; public String bandname; public int numberOfBandMember; public int bandType; } public List<BandInfoParam> fetchBandData(){ BandInfoDao bandInfoDao = new BandInfoDao(); List<BandInfoParam> bandInfoParamList = bandInfoDao.getBandData(); return bandInfoParamList; } }
package com.mokabuu.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import com.mokabuu.ri.BandInfoRI.BandInfoParam; public class BandInfoDao { public final static String GET_BANDDATA = "select * from bandinfo"; public List<BandInfoParam> getBandData() { List<BandInfoParam> result = null; try (Connection con = null; PreparedStatement ps = con.prepareStatement(GET_BANDDATA); ResultSet rs = ps.executeQuery();) { while (rs.next()) { BandInfoParam bandInfo = new BandInfoParam(); bandInfo.bandid = rs.getString("id"); bandInfo.bandname = rs.getString("name"); bandInfo.numberOfBandMember = rs.getInt("member"); bandInfo.bandType = rs.getInt("type"); result.add(bandInfo); } return result; } catch (SQLException e) { e.printStackTrace(); } return result; } }
こうするとDaoの方でエラーが出ます!
BandInfoParam bandInfo = new BandInfoParam();
ってしているところですね!
ここで「BandInfoRIの中にアクセスできねーよ!」って言われます。
No enclosing instance of type BandInfoRI is accessible.
Must qualify the allocation with an enclosing instance of type BandInfoRI
(e.g. x.new A() where x is an instance of BandInfoRI).
ってな感じですね!
package com.mokabuu.ri; import java.util.List; import com.mokabuu.dao.BandInfoDao; public class BandInfoRI { public static class BandInfoParam { public String bandid; public String bandname; public int numberOfBandMember; public int bandType; } public List<BandInfoParam> fetchBandData(){ BandInfoDao bandInfoDao = new BandInfoDao(); List<BandInfoParam> bandInfoParamList = bandInfoDao.getBandData(); return bandInfoParamList; } }
RIをちょこっと直して上げるだけです!
こうやってあげればアクセス出来るようになるので
先ほどのエラーは解消されます!
[adsense]