小编Nat*_*hes的帖子

在Java上使用String.endswith()方法

我有一个数组,我想检查数字中的最后一位数字.

例:

String[] types = {".png",".jpg",".gif"}

String image = "beauty.jpg";
// Note that this is wrong. The parameter required is a string not an array.
Boolean true = image.endswith(types); 
Run Code Online (Sandbox Code Playgroud)

请注意:我知道我可以使用for循环检查每个项目.

我想知道是否有更有效的方法来做到这一点.原因是图像字符串已经在不断变化的循环上.

java

5
推荐指数
2
解决办法
4007
查看次数

java:使用静态方法获取数据库连接

我正在研究现有的基于Java EE的应用程序.这具有以下连接数据库的方法:

public static java.sql.Connection connectionToDataBase(String jndiName,boolean flag)throws Exception 
{
DataSource ds =(javax.sql.DataSource) initCtx.lookup(jndiName);
return ds.getConnection();
    } catch (NamingException ne) {
            throw ne;
        } finally {
            try {
                if (initCtx != null)
                    initCtx.close();
            } catch (NamingException ne) {

                throw ne;
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是使用静态方法连接数据库是否正确?

java static static-methods

5
推荐指数
1
解决办法
2363
查看次数

Java线程安全 - 锁定整个静态类,但仅限于一种方法

我实现了一个静态帮助程序类,可以帮助缓存和检索数据库中的一些只读,不可变,非易失性数据.

(剥离)示例:

public class CacheHelper
{
    private static HashMap foos, bars;

    public static Foo getFoo(int fooId) { /* etc etc */ }
    public static Bar getBar(int barId) { /* etc etc */ }

    public static void reloadAllCaches()
    {
        //This is where I need it to lock access to all the other static methods
    }
}
Run Code Online (Sandbox Code Playgroud)

我为静态类读取它的方式,如果我将synchronized关键字添加到reloadAllCaches()方法,这将在该方法执行时对整个类应用锁.它是否正确?(编辑:是的,不正确.感谢您的回复.)

注意:我希望对getter方法的线程安全性和它们返回的对象保持不可知,因为这些数据永远不会发生变化,并希望尽快返回.

java static multithreading static-methods

5
推荐指数
1
解决办法
3788
查看次数

使用JdbcTemplate时转义单引号

我们正在使用JdbcTemplate来修改我们的底层Oracle数据库.我们是通过这种方法来做到这一点的update(String sql).

代码看起来有点如下:

String name = "My name's yellow";
String sql = "update FIELD set NAME = '" + name "' where ID = 10
jdbcTemplate.update(sql);
Run Code Online (Sandbox Code Playgroud)

这会导致错误:

java.sql.SQLException: ORA-00933: SQL command not properly ended
Run Code Online (Sandbox Code Playgroud)

问题是转义'name变量.

逃避这个角色最方便,最正确的方法是什么?

java oracle spring escaping jdbctemplate

5
推荐指数
1
解决办法
6358
查看次数

在notifyAll()之前未被线程锁定的同步对象

我想有一个布尔值来通知系统某些特定服务启动的部分.

由于一些奇怪的原因,我收到了错误java.lang.IllegalMonitorStateException: object not locked by thread before notifyAll().

奇怪的是,notifyAll()位于一个synchronized块内,该块控制我调用notifyAll()的对象.

我的班级开头是这样的:

public class MyService {

    public static Boolean notifier = Boolean.valueOf(false);

    @Override
    public void start() {
        synchronized (MyService.notifier) {
            MyService.notifier = Boolean.valueOf(true);
            MyService.notifier.notifyAll();
        }
    }

    @Override
    public void stop() {
        synchronized (MyService.notifier) {
            MyService.notifier = Boolean.valueOf(false);
            MyService.notifier.notifyAll();
        }
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我正在研究一个Android应用程序.我认为它不应该影响任何事情,但是如果影响java的工作方式,我会用该注释补充问题.

如果对象锁定在同步块中,为什么会出现异常?

java multithreading synchronization synchronized java-threads

5
推荐指数
1
解决办法
9669
查看次数

尝试关闭I/O对象时"找不到符号"

public static int howMany(String FileName)
{
    BufferedReader br = null;

    try
    {
        FileInputStream fis = new FileInputStream(FileName);
        DataInputStream dis = new DataInputStream(fis);
        br = new BufferedReader(new InputStreamReader(dis));
    }
    catch (FileNotFoundException e)
    {
        System.out.print("FILE DOESN'T EXIST");
    }
    finally
    {
        fis.close();
        dis.close();
        br.close();
    }


    String input;
    int count = 0;

    try
    {

        while ((input = br.readLine()) != null)
        {
            count++;
        }

    }
    catch (IOException e) 
    {
        System.out.print("I/O STREAM EXCEPTION");
    }


    return count;
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我无法关闭任何I/O对象.即使我导入了所有的I/O库(导入java.io.*;)并启动了所有对象,fis.close(),dis.close(),br.close()都给我找不到符号.

java exception-handling

5
推荐指数
1
解决办法
3014
查看次数

Junit最佳实践:调用多个私有方法的公共方法

我开始为遗留代码库编写JUnit测试用例.其中一个公共方法有多个if语句,并且基于一个条件,它调用不同的私有方法.
我应该只编写一种测试方法并测试所有条件吗?每种情况的一种方法?

如果我为每个if条件编写单独的方法,我不会失去一致性吗?

测试私有方法的方法是什么?私有方法逻辑可能比公共方法更复杂.

java junit unit-testing junit4

5
推荐指数
1
解决办法
1026
查看次数

春天的线程安全会话bean的最佳实践?

我想知道什么是使会话bean线程安全的最佳实践.

我们假设我有这个会话bean及其服务:

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
class Cart {

    private HashSet<Item> items = new HashSet<Item>();

    private int counter = 0;

    public HashSet<Item> getItems() {
        return items;
    }

    public int getCounter() {
        return counter;
    }

}

@Service
class CartService {

    @Autowired
    private Cart cart;

    public void addItem(Item item) throws FullException {
        if (cart.getCounter() > 1234) {
            throw new FullException();

        }
        cart.getItems().add(item);
    }

}
Run Code Online (Sandbox Code Playgroud)

上面的代码不是线程安全的,并且当多个线程(同一会话,例如异步Ajax请求)执行时,将导致问题CartService.addItem(Item).

我想我不是第一个遇到这个问题的人,但是我的研究并没有带给我最佳实践.

我可以做的最糟糕的事情是同步addItem(),因为CartService由多个会话共享.在购物车中同步在CartService.addItem()我看来同样糟糕,因为Cart是一个代理bean.我理解,因为所有会话仍然会在同一个对象上同步.

一种可接受的解决办法似乎是在同步块Cart.getItems()CartService.addItem():

@Service
class CartService …
Run Code Online (Sandbox Code Playgroud)

java session spring-mvc thread-safety

5
推荐指数
1
解决办法
3228
查看次数

如果 catch 抛出异常,我应该如何处理它们?

我有一个简单的编码场景,如:

class A
{

    public static void main(String[] args) 
    { 
        try{
            //some exception
        }
        catch(Exception e)
        {
           //Again some exception
        }
        finally
        {
            System.out.println("Finally executed");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题:

  1. 有没有办法处理 catch 中的异常?如果是,那么如何?
  2. 如果 finally 块有异常怎么办,有没有办法处理它们?
  3. 或者在 catch 或 finally 块中出现异常只是糟糕的编程习惯吗?

java exception-handling exception

5
推荐指数
1
解决办法
100
查看次数

Java连接字符串与静态字符串

我试图更好地理解字符串.我基本上是在制作一个需要大量字符串的程序.但是,很多字符串非常非常相似,只需要在字符串末尾使用不同的单词.

例如

String one = "I went to the store and bought milk"
String two = "I went to the store and bought eggs"
String three = "I went to the store and bought cheese"
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,在处理字符串时最适合采用哪种方法?将2个字符串连接在一起有什么好处而不仅仅是静态字符串,例如性能或内存管理?

例如

String one = "I went to the store and bought "
String two = "milk" 
String three = "cheese"
String four = one + two
String five = one + three
Run Code Online (Sandbox Code Playgroud)

我只想弄清楚处理所有这些字符串的最佳方法.(如果它有助于放置我正在使用的一些字符串,我目前有50个,但这个数字可以盈余很多)

java string string-concatenation

5
推荐指数
1
解决办法
1682
查看次数